Persist currentUser firebase with React Native

Asked

Viewed 676 times

0

This function is triggered by clicking the Login button:

export const loginUser = ({ email, password }) => {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(user => {
      firebase.database().ref('/admins').once('value')
      .then(snapshot => {
        const admins = _.map(snapshot.val(), (val, uid) => {
          return { ...val, uid };
        });
        if (admins.some((item) => item.s_email === email)) {
          typeAdmin(dispatch);
        } else typeStudent(dispatch);
        loginUserSuccess(dispatch, user);
      });
    }).catch(() => loginUserFail(dispatch));
  });
};
};

Current Behavior

When leaving the application and back it is necessary to relocate to access the data of the currentUser.

Expected Behavior

When leaving the application keep the currentUser of the session and back nothing have been lost.

2 answers

1


I’ve been through it and I’ve managed to solve it in a simple way:

isLogged() {
    if(firebase.auth().currentUser){
        //Esta logado então faça algo ...
    }
}

componentDidMount() {
    isLogged();
}

The isLogged() method must be called after the firebase boot has been done or will generate an error.

  • Thank you very much, that solution worked. I chose to store the user status for Asyncstorage, so I keep the information even if the application is closed. I voted -1 in your comment unintentionally and I’m not managing to change. Thanks for the help

0

I’m trying to do it this way, but every time I close the app, currentUser stays NULL

       firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(() => {
          firebase.auth().signInWithEmailAndPassword(user, pass).then(loginUserSuccess)
          .catch(error => {
            console.log('erro');
           })
        })

that console.log() below shows null whenever I open the APP

  isLogged() {
    console.log(firebase.auth().currentUser);
    if(firebase.auth().currentUser){
      this.props.navigation.replace('Fazendas');
    }
  }

  componentDidMount() {
    this.isLogged();
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.