I have problem in firebase authentication – React Native.
using OnAuthStateChanged
the login process was successfully executed. but when page is refreshed/reloaded, in debugger it shows value user = 'null'
,
even though I’m logged in.
import {onAuthStateChanged} from 'firebase/auth';
import React, {useEffect} from 'react';
import {auth} from '../../utils/firebase';
export default function GetStarted({navigation}) {
useEffect(() => {
onAuthStateChanged(auth, user => {
console.log('user :', user);
if (user) {
navigation.replace('MainApp');
} else {
//
}
});
}, [navigation]);
when Logged In —-
Debugger: Loggin
When Reload/Refresh Page —
Debugger: Reload/Refresh Page
using React Native V0.71, Firebase V9
can anyone help me to solve this?, i really appreciate the help
2
Answers
It sounds like you may be running on a platform where the Firebase SDK doesn’t automatically persist user data. Have a look at the documentation on authentication state persistence to find your options.
I you are using react-navigation v6 I strongly suggest you use the logic below
you should never user navigation.replace(‘MainApp’) to manually navigate between stacks on auth state changes. Simply put here we’re displaying a splash screen until the onAuthStateChanged finishes running. if finished we check if the user is logged in. if yes authState is true else false. and we display MainApp or authStack accordingly.
Edit
I noticed firebase uses AsyncStorage from react native for storing user’s session (Whether it is a secure way to store it I don’t think so ) so you may run into a warning saying that AsyncStorage must be imported from @react-native-async-storage/async-storage.