I successfully check user's authentication state with onAuthStateChange observer and redirect user to the Dashboard page (react-native project). However, on the dashboard I already want to show some user specific data, e.g. enrolled programs/statistics. For that I need currentUser object to be initialised and populated, which takes some time (I need uid from there to get some data from Database). Thus, i'm looking for some way to wait until this process finishes successfully. What I'm trying to do it to use async/await syntax in componentDidMount, but the result returned is null. (Same syntax successfully works in other screens, but fails in the first one)
async componentDidMount() {
try {
let uid = await firebase.auth().currentUser.uid;
console.log(uid);
} catch(error) {
console.log(error);
}
}
What could be the best way to wait for currentUser object being loaded using async/await syntax? I believe that the reason could be that firebase returns null as the first result and then correct uid as the second one.
For now for the workaround, I'm using simple setInterval function, but I do not want to increase amount of loading time that much.
let waitForCurrentUser = setInterval(() => {
if ( firebase.auth().currentUser.uid !== null ) {
clearInterval(waitForCurrentUser);
let uid = firebase.auth().currentUser.uid;
this.setState({uid});
return firebase.auth().currentUser.uid;
} else {
console.log('Wait for it');
}
}, 700);
The equivalence of setInterval is : //calling the asynchronous function waitForCurrentUser(function(uid){ if(uid) console.log('the user id is',uid) })
async waitForCurrentUser(userIdIs){
try {
let uid = await firebase.auth().currentUser.uid;
if(uid)
{
clearInterval(waitForCurrentUser);
this.setState({uid});
userIdIs(uid);
}
else {
console.log('Wait for it');
}
}
catch(e){
console.log(e)
}
// return userIdIs(uid);//returns promise
};
Cheers :)
async getUid() {
let user = await firebaseApp.auth().currentUser;
let email = await user.uid;
}
Hope it's usefull for you
来源:https://stackoverflow.com/questions/43821921/get-firebase-auth-currentuser-with-async-await