In Firebase 2 I was able to do a synchronous check to see if the user was logged in, e.g:
if (!ref.getAuth()) ..go to login page
else ..show page
I can access the currentUser
state with firebase.auth().currentUser
so I tried to do:
if (!firebase.auth().currentUser) ..go to login page
else ..show page
The problem is that this is always initially null, so it redirects to the login page, then a few moments later onAuthStateChanged
happens and the user is logged in.
Is there still a way to synchronously check this? Or otherwise is there a promise I can listen to so that I can show a loading spinner or something? Thanks.
GetAuth. Returns the FirebaseAuth object for an App. Creates the FirebaseAuth if required. The FirebaseApp to use for the FirebaseAuth object.
If a user isn't signed in, CurrentUser returns null. Note: CurrentUser might also return null because the auth object has not finished initializing.
According to the documentation, the onAuthStateChanged() function returns. The unsubscribe function for the observer. So you can just: var unsubscribe = firebase.
onAuthStateChanged. Adds an observer for changes to the user's sign-in state. Prior to 4.0. 0, this triggered the observer when users were signed in, signed out, or when the user's ID token changed in situations such as token expiry or password change.
I've been using an auth state listener to determine if the user is signed in.
auth.onAuthStateChanged(function(user) {
console.log('authStateChanged', user);
if (user) {
console.log("Welcome UID:" + user.uid);
}
});
When you attach that listener right away, it will fire with the correct state.
When I run the app, sign in and reload the page, the log outputs:
authStateChanged Fl {...}
Welcome UID:052289713245805425655890E9024AB4ADBA5404B3C0
So you can use the first time the listener is called to detect if the user is already signed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With