0

I get logged out every-time I refresh, here's the code I am using. nothing special just simple conditional render in React.

What is causing this?

I tried using set persistence but that's giving errors.

export default function GAuth(){
  const [currentUser, setCurrentUser] = useState(null);

  let auth = getAuth();
  let GoogleProvider = new GoogleAuthProvider()

  
  function handleSubmit(event) {
    event.preventDefault();
    signInWithPopup(auth, GoogleProvider)
    .then((response) => {setCurrentUser(response.user)})
    .catch((err) => {alert(err.message)})
  }

  function authChecker(){
      if(currentUser){
          console.log("User is logged in")
          return <FullApp/>

      }else{
          console.log("User is not logged in")
          return (<div className="auth-page">
                  <form className="signup-form" onSubmit={handleSubmit}>
                      <h1>You have No Notes, Sign In to create one</h1>
                      <input className="first-note" type="submit" value={"Sign in with google"} />
                  </form>
              </div>)
      }
  }

  
  //returning objects to the DOM
  return (
      <div>
          {authChecker()}
      </div>
      
  )
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
heatblast
  • 1
  • 1
  • Does this answer your question? [Losing useState Value on Refresh in React.js](https://stackoverflow.com/questions/70832675/losing-usestate-value-on-refresh-in-react-js) – deta utama Jul 02 '22 at 13:06

1 Answers1

0

Firebase automatically persists the user credentials and restores them on most browser based environments. But restoring them requires it to make a call to the server (e.g. to check if the account has been disabled), and by the time your code checks currentUser the call hasn't completed yet.

That's why you should use an auth state listener to get notified when the authentication state changes, as shown in the first snippet in the documentation on getting the current user:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

With this, Firebase will automatically call your handler when it has finished restoring the user credentials, and you can then update the UI to reflect that state.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807