Reputation: 5565
I am trying to log in using Firebase Authentication, the login process works.
auth.onAuthStateChanged(function(user) {
if(user) {
console.log('Logged in');
console.log(user.displayName);
document.getElementById('userName').textContent = user.displayName;
} else {
window.location = '../login';
}
});
The above code works as expected, it logs user display name and the text 'Logged in'.
console.log(firebase.auth().currentUser);
This code is present on the same page but surprisingly doesn't works! It logs null
. This is what the official documentation says to retrieve the currently logged in user
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
Now in my case the code doesn't works, always prints null
.
Upvotes: 0
Views: 690
Reputation: 18585
Don't use .currentUser
for that. .onAuthStateChanged
is where you want to fire all your UI modifying functions/methods from. .onAuthStateChanged
takes a second to initialize, that's why currentUser
is empty.
BTW, I've built out the auth system boilerplate with all 6 authentication types working. It's on Github. Demo of it is here.
Upvotes: 1
Reputation: 30868
currentUser will be correctly populated after the onAuthStateChanged observer triggers. Until then it will be null. currentUser is synchronous but initial state determination is determined asynchronously.
Upvotes: 0