Home > Software design >  How to save a session on firebase 9?
How to save a session on firebase 9?

Time:06-21

please help. I'm trying to ensure that the user does not log out after reloading the page.

  const signUp = async (loginEmail, loginPassword) => {
    const auth = getAuth()
    setPersistence(auth, browserSessionPersistence)
      .then(({ user }) => {
        dispatch(
          setUser({
            email: user.email,
            id: user.uid,
            token: user.accessToken,
          })
        )
        return signInWithEmailAndPassword(auth, loginEmail, loginPassword)
      })
      .catch((error) => {
        console.log(error.message)
      })
  }

This is what the example looks like in the official documentation

const auth = getAuth();
setPersistence(auth, browserSessionPersistence)
  .then(() => {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return signInWithEmailAndPassword(auth, email, password);
  })
  .catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
  });

CodePudding user response:

The recommended way to get the current user is by setting an observer on the Auth object:

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
    // ...
  }
});

documentation

  • Related