So I'm developing my very first React native app with Firebase and I have the following structure in my code:
ComponentDidMount(){
this.verifySession();
console.log("Component did mount");
}
verifySession = () =>{
console.log("inside VS");
firebase.auth().onAuthStateChanged(user =>{
if(user){
this.props.navigation.navigate('Dashboard');
console.log("dashboard");
}else{
this.props.navigation.navigate('Login');
console.log("Login");
}
});
}
Problem is, my verifySession function is not getting triggered. Actually, I'm not getting any logs so I think ComponentDidMount is not being executed either. This code is placed within my LoadingScreen component.
Here's my app.js where I initialize the Firebase conf:
import * as firebase from 'firebase';
import {firebaseConfig} from './data/config';
const Stack = createStackNavigator();
firebase.initializeApp(firebaseConfig);
I've also tried the following for my LoadingScreen:
import Dashboard from './dashboard';
import Login from './login';
render(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
return (<Dashboard/>);
}else{
return (<Login/>);
}
});
return(
<View>
<Text>Verifying session...</Text>
</View>
)
}
Login should get rendered but instead it shows "Verifying session" which makes me think if the statement is not getting executed at all.
Any thoughts/recommendations on this matter will be appreciated.
onAuthStateChanged
is meant to add an observer and not to be called directly. Could be it's not firing because the user's login-status is not changing at all and you're not attempting to sign-in anyone in, so there's nothing to trigger it. Try implementing auth().createUserWithEmailAndPassword(email, password)
or `auth().signInWithEmailAndPassword(email, password)' and test out user creation/sign-in.
This article may also be of use; it puts an auth observer in a separate component and allows you to navigate between two navigation stacks based on user's login status: https://heartbeat.fritz.ai/how-to-manage-authentication-flows-in-react-native-with-react-navigation-v5-and-firebase-860f57ae20d3
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.