Reputation: 25
Please help me i want to get the user UID and save it in a global variable and use it wherever required i am using this method but its not working
'''
var userUID= null;
firebase.auth().onAuthStateChanged(function(user){
if(user){
console.log("logged in");
userUID=firebase.auth().currentUser.uid;
console.log(userUID); //This statement is printing properly
}
else{
console.log("Not Logged In");
}
});
console.log(userUID); // This statement is returning null (i want this to work)
'''
Upvotes: 0
Views: 150
Reputation: 1448
The problem here is that Firebase takes some time to log in automatically. While it's waiting to log in, onAuthStateChanged
will not be called, and userUID
will still be null when JS proceeds on to execute console.log(userUID)
.
Unfortunately, the real solution to this is to change your app's structure to be able to handle a null userUID
. It's likely that it is possible for a non-logged-in user to browse this page, and therefore it probably needs to be handled anyway. There are two ways to do this:
userUID
is null, and disable features based on that;onAuthStateChanged
is called, so that your code is always executed with a valid userUID
. This can be done with Promises or callbacks as you desire.Upvotes: 1