Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page reloads again and again after authenciated keycloak

I follow these steps (https://scalac.io/user-authentication-keycloak-1/) to authenciate my react app with keycloak. But one small different thing here is that I am using react hook to manage my state(the code below). That causes the page reload again and again. Do you have any idea?

import React, { useState, useEffect } from "react";
import UserInfo from "./UserInfo";
import Logout from "./Logout";
import Keycloak from "keycloak-js";

// The difference is here
function Secured(props) {
  const [keycloak, setKeycloak] = useState(null);
  const [isAuthenciated, setAuthenciation] = useState(false);
  useEffect(() => {
    const keycloak = Keycloak("/keycloak.json");
    keycloak.init({ onLoad: "login-required" }).then(authenticated => {
      setKeycloak(keycloak);
      setAuthenciation(authenticated);
    });
  });

  if (keycloak) {
    if (isAuthenciated)
      return (
        <div>
          <p>
            This is a Keycloak-secured component of your application. You
            shouldn't be able to see this unless you've authenticated with
            Keycloak.
          </p>
          <UserInfo keycloak={this.state.keycloak} />
          <Logout keycloak={this.state.keycloak} />
        </div>
      );
    else return <div>Unable to authenticate!</div>;
  }
  return <div>Initializing Keycloak...</div>;
}

export default Secured;
like image 957
BadJuju Avatar asked Sep 16 '25 04:09

BadJuju


1 Answers

It seems like you forgot to include the dependencies of useEffect. Not setting them makes useEffect to run on every render. In case you only want it to run once we set the dependencies as an empty array.

useEffect(() => {
    const keycloak = Keycloak("/keycloak.json");
    keycloak.init({ onLoad: "login-required" }).then(authenticated => {
        setKeycloak(keycloak);
        setAuthenciation(authenticated);
    });
}, []);
like image 150
Alvaro Avatar answered Sep 19 '25 15:09

Alvaro