Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for FirebaseAuth to finish initializing?

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()?

like image 261
Jeffrey Lopez Avatar asked Aug 30 '16 15:08

Jeffrey Lopez


3 Answers

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

firebase.auth().onAuthStateChanged(user => init_your_app);
like image 168
timkay Avatar answered Oct 18 '22 22:10

timkay


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

like image 7
GintsGints Avatar answered Oct 18 '22 22:10

GintsGints


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/>;
    }
}


like image 6
Harsh Verma Avatar answered Oct 18 '22 23:10

Harsh Verma