Search code examples
reactjsfirebasereact-lifecycle

How to verify login and render conditionally (ReactJS and Firebase)?


I want to make sure that a user is logged in before running rendering either A or B.

When I console.log it, I get a true in return when I check if I'm logged in, however wrong if-statement gets rendered.

I think that it's because firebase takes its time to load and my function renders before firebase has done this.

const renderForm = () => {

  let isLoggedin = false;
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      isLoggedin = true;
      console.log(isLoggedin + " Logged in")
    } else {
      isLoggedin = false;
    }
  });
  return (
    <div>
      {isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}

    </div>
  )
}

Can someone explain how I should go ahead and solve this? Obviously, I want to render the component if user is logged in.

Thanks,


Solution

  • You need to convert isLoggedIn to React state and not local variable.

    As per below code, when isLoggedIn is false, you should see <p>You have to log in</p> else AddNewCountryForm component should render.

       const renderForm = () => {
    
          const [isLoggedin, setIsLoggedIn] = React.useState(false);
          firebase.auth().onAuthStateChanged(function(user) {
            setIsLoggedIn(!!user);
          });
          return (
            <div>
              {isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}
    
            </div>
          )
        }
    

    Hope it helps.