3

I have used context api to manage the user login state .I also used firebase auth persistance to keep the user logged in after page reload but it isn't working :/ In my session storage the user info is getting saved but after page reload user is automatically logged out of the application.

loginContext.js

export const LoginContext = createContext();
const LoginContextProvider = ({ children }) => {
  const [loggedInUser, setLoggedInUser] = useState({});
  return (
    <LoginContext.Provider value={[loggedInUser, setLoggedInUser]}>
      {children}
    </LoginContext.Provider>
  );
};

Login.js

const gmailProvider = new firebase.auth.GoogleAuthProvider();

  const handleGmailSignIn = () => {
    firebase
      .auth()
      .setPersistence(firebase.auth.Auth.Persistence.SESSION)
      .then(() => {
        firebase
          .auth()
          .signInWithPopup(gmailProvider)
          .then((result) => {
            const { displayName, email, photoURL } = result.user;
            const signedInUser = {
              isSignedIn: true,
              name: displayName,
              email: email,
              photoURL: photoURL,
            };
            // setUserToken();
            setLoggedInUser(signedInUser);
            history.replace(from);
            console.log(displayName, email);
          });
      })

      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        const credential = error.credential;
        // ...
      });
  };
Shahriar
  • 107
  • 2
  • 10

1 Answers1

3

On page refresh, Firebase Auth has to load the auth credentials from the cache and reverify them. This is an asynchronous process and can take a few seconds resulting on the 'user not logged in' state.

it's important to listen for the auth state to change with

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Source: https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user

There are plenty of tutorials that implement this in several different ways, you can find some here: https://johnwcassidy.medium.com/firebase-authentication-hooks-and-context-d0e47395f402 https://stackoverflow.com/a/50204490/2301161

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20
  • I guess ```const auth = getAuth(); const currentUser = auth.currentUser; ``` the correct way of retrieving current user – Harshil Modi Mar 06 '22 at 13:48