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()?
Using the modern API, simply wait for auth state to change:
firebase.auth().onAuthStateChanged(user => init_your_app);
                        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
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/>;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With