Reputation: 198
I have not been able to persist a firebase session in my react-native application. This question is nearly identical to React Native - Firebase auth persistence not working but the answer provided there has not worked for me.
Currently I log in as shown below:
export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch(() => loginUserFailed(dispatch))
};
};
My session is created and I have access to the user object stored on firebase.
When I Cmd+R or when I close the application and reopen it my session is gone. I have run the following in the componentWillMount() section of my app.js file:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user is logged');
} else {
console.log('not logged in')
}
});
Whenever I refresh the app or close it completely and reopen I get the 'not logged in' response.
I have also tried querying:
firebase.auth().currentUser
but get the same issue where it returns null
What am I doing wrong?
Is there a particular way to keep the session active that I am missing?
Upvotes: 7
Views: 4636
Reputation: 198
It's been a while since I posted this question but I thought I would post my solution.
As it turns out my initial set up (kind of) worked. By that I mean that onAuthStateChanged was taking some time to hear back from firebase and during that time the rest of the application loaded thinking that the user was not logged in, due to that being the default state.
I managed to get around this by moving the onAuthStateChanged logic out of the app.js and in to the initial home page in componentWillMount. which now looks like this:
componentWillMount() {
const { navigate } = this.props.navigation;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
SplashScreen.hide()
this.setState({ loading: false })
this.props.persistedUserLoginSuccess({user, navigate})
this.props.fetchUserData();
} else {
SplashScreen.hide()
this.setState({ loading: false })
}
});
Also, I managed to better the user experience by forcing the splash screen to stay up which the auth was being queried. Upon completion the splash screen was hidden and the application loaded as either a logged in application or one where the user had not yet logged in.
Upvotes: 3
Reputation: 1527
This issue is because you are not doing Firebase.auth().signOut() after once loggedIn. Try to signOut (for testing you can always sign out in componentWillMount function) and you will be able to see the onAuthStateChanged notification.
Upvotes: 0