Nati Reitblat
Nati Reitblat

Reputation: 35

How do i add a firebase listener that would wait until firebase auth has loaded?

addEventListener('DOMContentLoaded', ()=>{
    if(firebase.auth().currentUser == null)
        document.getElementById("loggedOut").hidden = false;

    else
        document.getElementById("loggedIn").hidden = false;    
});

it takes the firebase auth data base a second load so when I run this code it will always say that firebase.auth().currentUser == null is true. Even though if I get a button to print firebase.auth().currentUser it'll give me the real answer.

Upvotes: 0

Views: 467

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317958

You should use an auth state listener to get a callback when the current user is known, as described in the documentation:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // User is signed out.
  }
});

firebase.auth().currentUser isn't going to be accurate until the first time this callback is invoked, so you should depend on this callback to render your UI correctly.

Upvotes: 2

Related Questions