Home > other >  Login/Logout Button Rerendering
Login/Logout Button Rerendering

Time:10-22

I'm trying to change the state of Login/Logout button without refreshing the page on Nav. I used useContext for state management. The code I wrote keeps changing the state of button automatically. I desire to know why this is happening.

  1. Context API
export function LoginContextProvider({ children }) {
  const [loggedin, setLoggedin] = useState(false);

  return (
    <LoginContext.Provider value={{ loggedin, setLoggedin }}>
      {children}
    </LoginContext.Provider>
  );
}
  1. Nav.js
const token = localStorage.getItem('access_token');
  const removeToken = () => {
    localStorage.removeItem('access_token');
  };

  const { loggedin, setLoggedin } = useLoginContext();

  useEffect(() => {
    setLoggedin(!loggedin);
  }, [token, loggedin, setLoggedin]);

return (
...
<NavRight> 
  {loggedin ? (
    <NavSigninBtn
      onClick={() => {
        removeToken();
      }}
    >
    Logout
    </NavSigninBtn>
  ) : (
    <NavSigninBtn
      onClick={() => {
        history.push('/signin');
      }}
    >
      Login
   </NavSigninBtn>
  )}
</NavRight>
)

CodePudding user response:

The problem lies in your useEffect hook.Your useEffect has a dependency of two variables and a an setstate function.When you have state and setstate as the dependency then the useEffeect will be called twice once for the state and another for the setdstate.So remove the dependencies .Keep the token as the only dependency.

CodePudding user response:

You are infinitely resetting the value of loggedin in your useEffect. Remove your useEffect entirely and instead do this in your render method:

<NavRight>
  <NavSigninBtn
    onClick={() => {
      if(!!token){
        removeToken();
      } else {
        history.push('/signin');
      }
    }}
  >
    {!!token ? "Logout" : "Login"}
  </NavSigninBtn>
</NavRight>
  • Related