Search code examples
javascriptfirebasefirebase-authenticationgoogle-authentication

Window loading and Firebase Authentication


I am creating a website that relies on Firebase Authentication and uses Google Auth. After the user logs in on a separate page, my website redirects the user to the "main page" where the window loads based on the user that is logged in.

However, if I check if a logged-in user exists at "window.onload," it is always false. Instead, if I run an async function, and then check for a logged-in user after a ".then", I get true back.

This leads me to hypothesize that "window.onload" fires quicker than the page can recognize the logged-in user.

How do I fix this problem and make sure that the logged-in user loads before I call on my async function? I am pretty sure firebase.auth() itself is async, but for some reason .then does not seem to work with it.

<script>

  window.onload = loadPage();
  
  function loadPage()
  {
    var user = firebase.auth().currentUser;
    if(user)
      console.log("userFound before async"); //Does NOT console log

    asyncFunction().then(function()
    {
      var user = firebase.auth().currentUser;
      if(user)
        console.log("userFound after async"); //Does console log
    })
}

</script>

Solution

  • If you want to do something with the currently signed in user, you should use an auth state observer to register a callback that gets invoked when the user object is first known. It won't be available when the page initially loads, as you have described in your question.

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

    Depending on the completion of other async functions is not advisable - use the observer to know for sure. It will be invoked whenever it is first known for sure if a user is signed in or not, and again with each change in sign-in state.