简体   繁体   中英

Persist auth state in react/react native for Firebase

I am using react native for an ios app and firebase for authentication. Every time I leave the app and come back, it asks for a login. I want to persist the firebase login but don't really know where to put it.

I know I need to put this in:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)

I have the following signIn function that runs when the login button is pressed on the signInScreen:

const signIn = async () => {
    setLoading(true);
    try {
      await firebase.signIn(email, password);
      const uid = firebase.getCurrentUser().uid;
      const userInfo = await firebase.getUserInfo(uid);
      const emailArr = userInfo.email.split("@");
      setUser({
        username: emailArr[0],
        email: userInfo.email,
        uid,
        isLoggedIn: true,
      });
    } catch (error) {
      alert(error.message);
    } finally {
      isMounted.current && setLoading(false);
    }
  };

I have the following signIn stuff in my firebaseContext:

const Firebase = {
  getCurrentUser: () => {
    return firebase.auth().currentUser;
  },

  signIn: async (email, password) => {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  },

  getUserInfo: async (uid) => {
    try {
      const user = await db.collection("users").doc(uid).get();
      if (user.exists) {
        return user.data();
      }
    } catch (error) {
      console.log("Error @getUserInfo", error);
    }
  },

  logOut: async () => {
    return firebase
      .auth()
      .signOut()
      .then(() => {
        return true;
      })
      .catch((error) => {
        console.log("Error @logout", error);
      });
  },
};

Where do I put the persist code I listed above from the docs?

Thanks!

When do you check if someon is signed in or not?

From the code shown it looks like you check it manuelly by calling currentUser . You have to consider that the persistance of auth state is asynchronous. That means if you call currentUser on auth before the localy saved auth state is loaded you would get there null and thing that the user is not signed in.

To get the auth state Firebase recommend to use the onAuthStateChanges event listener. With that you can listen to auth state changes no matter if you logged in or the persistet auth state is loaded.

The usage is very simple:

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

That is the reson I asked where you check if someon is signed in or not. If I could see that code I could help you adopt it to use that event listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM