Dominic Tobias Dominic Tobias - 5 months ago 50
Javascript Question

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.

Answer

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.

Comments