How to wait for FirebaseAuth to finish initializing?

13,821

Solution 1

Using the modern API, simply wait for auth state to change:

firebase.auth().onAuthStateChanged(user => init_your_app);

Solution 2

You can create function which returns promise, and await where needed:

function getCurrentUser(auth) {
  return new Promise((resolve, reject) => {
     const unsubscribe = auth.onAuthStateChanged(user => {
        unsubscribe();
        resolve(user);
     }, reject);
  });
}

Check this - https://github.com/firebase/firebase-js-sdk/issues/462

Solution 3

For React users who are asking the same question :

react-firebase-hooks has a hook called useAuthState that can prove to be helpful for checking the state of firebase auth. Following is a very common use-case I think.

import {useAuthState} from "react-firebase-hooks/auth";
import React from "react";

export default function AllowIfAuth() {
    const [user, loading, error] = useAuthState(auth);
    if (loading) {
        return <div> Loading... </div>;
    } else if (user) {
        return <div> Some Content </div>;
    } else if (error) {
        return <div>There was an authentication error.</div>;
    } else {
        return <LoginPage/>;
    }
}


Solution 4

Cannot believe that I have to do this (as there is no official API by Google). I have to use one additional boolean...

let isAuthReady = false

firebase.auth().onAuthStateChanged((user) => {
  store.commit('setUser', user)

  if (!isAuthReady) {
    isAuthReady = true
    init()
  }
})
Share:
13,821
zepolyerf
Author by

zepolyerf

Updated on June 27, 2022

Comments

  • zepolyerf
    zepolyerf about 2 years

    Integrated Firebase Authentication to my app. Everything seems to be fine, until I noticed the issue wherein I open the app, it shows me the login screen, even though there is already a user signed in.

    Exiting the app and launching it again solves the problem (app no longer asks the user to sign in again), though it provides the users a very bad experience.

    I've read the docs, and apparently, calling FirebaseAuth.getInstance().getCurrentUser() might return null if auth haven't finished initializing. I'm assuming that's the reason why the issue happens. So I wonder if there is a way to wait for FirebaseAuth to finish its initialization before I can call getCurrentUser()?