1

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.

1
  • 1
    Please share the code that you think is not working as intended Commented Jul 5, 2021 at 17:52

2 Answers 2

1

I created a dedicated hook in React 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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.