0

I successfully check the user's authentication state with onAuthStateChange observer and redirect the user to the profile page. However, I already want to show some user-specific data on the profile, (e.g. description). For that, I need the currentUser object to be initialized and populated, which takes some time (I need uid from there to get some data from firestore). Thus, I'm looking for some way to wait until this process finishes successfully. I'm trying to use async/await syntax on the profile page, but the result returned is null.

For now, I'm using local storage when I want to get the data to the next page.

What could be the best way to wait for the currentUser object to be loaded using async/await syntax? I believe that the reason could be that firebase returns null as the first result and then correct uid - after some auth functionality is loaded.

Netzer
  • 37
  • 1
  • 9

2 Answers2

0

What you're describing is working as expected. If you want code to run only after the user's sign-in state has been restored, it needs to be inside an auth state change listener as shown in the first code snippet in the documentation on getting the currently signed in user:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    //  Your code that needs an active user goes here
  } else {
    // User is signed out
    // ...
  }
});

There is no way to use await here, as onAuthStateChanged doesn't return a promise, but instead fires each time the user's authentication state changes.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

I created a dedicated hook in React js to handle this:

import { useEffect, useState } from "react";
import { User } from "firebase/auth";
import { auth } from "../lib/firebase";

const useAuth = () => {
    const [user, setUser] = useState<User | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        return auth.onAuthStateChanged(user => {
            setUser(user);
            setIsLoading(false);
        });
    }, []);

    return {
        user, isLoading
    };
}

export default useAuth;
Damiano
  • 1
  • 1
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 23 '22 at 03:20