Home > Mobile >  How do I change the “log in” button to say “log out” whenever I am logged In
How do I change the “log in” button to say “log out” whenever I am logged In

Time:12-17

I’m using createUserWithEmailAndPassword and signInWithEmailAndPassword for my React website.

when I log in on the log in page, it navigates back to the home page, on the home page in the header, how do I get the “login” button to change to say “log out”.

I tried a useEffect with onAuthStateChange in it, but I don’t know the exact code for it to make it change the jsx element button from “log in” to “log out”

CodePudding user response:

Do you have a variable that identifies if your users are logged in? If so you can do a conditional operator like so: (This could be either in the button or above the button depending on how different you need login & logout to be)

[Are you logged in] ? [Yes, then...] : [No then...]

For example

Var loggedIn = false
return (<>
<Button>{loggedIn ? "Log Out" : "Login" }</Button>
</>)

(This might not be fully syntactically correct but should be enough to get you started)

CodePudding user response:

I would suggest using the localStorage to store the state of your user after login like this localStorage.setItem('isloggedIn',true) and after logout do this localStorage.setItem('isloggedIn',false).

So for your Button you can make a conditional render for it:

const isloggedIn = localStorage.getItem('isloggedIn');

return (
  <div>
    {
      isloggedIn ?
        <Button onClick={handleLogOut}>
          Log Out
        </Button>
        :
        <Button onClick={handleLogIn}>
          Log In
        </Button>
    }
  </div>
)

  • Related