Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase 3 - ref.getAuth() equivalent

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.

like image 214
Dominic Avatar asked May 21 '16 20:05

Dominic


People also ask

What is GetAuth firebase?

GetAuth. Returns the FirebaseAuth object for an App. Creates the FirebaseAuth if required. The FirebaseApp to use for the FirebaseAuth object.

What does firebase auth () CurrentUser return?

If a user isn't signed in, CurrentUser returns null. Note: CurrentUser might also return null because the auth object has not finished initializing.

What is onAuthStateChanged in firebase?

According to the documentation, the onAuthStateChanged() function returns. The unsubscribe function for the observer. So you can just: var unsubscribe = firebase.

What triggers onAuthStateChanged?

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.


1 Answers

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.

like image 92
Frank van Puffelen Avatar answered Oct 16 '22 07:10

Frank van Puffelen