spheroidic
spheroidic

Reputation: 199

How can I check for an already logged-in user on initial render using Firestore?

I'm seeing an issue where Firestore's auth.currentUser is always null on my app's initial render. Here's a simplified version of my component:

import ...

const [isInitialRender, setIsInitialRender] = useState(true);

const firebaseConfig = {...}
const app = initializeApp(firebaseConfig); 

// Auth
export const auth = getAuth();
connectAuthEmulator(auth, "http://localhost:9099"); // Maybe part of the problem?

// DB
export const db = getFirestore();
connectFirestoreEmulator(db, "localhost", 8080);   

useEffect(() => {
    if (isInitialRender) {
      setIsInitialRender(() => false);

      //Attempt to check existing authentication
      if (auth.currentUser) console.log("Logged in"); // Never logs
      
      return;
    }
    
    if (auth.currentUser) console.log("Logged in"); // Works fine
}

I stole my login function from the docs. It looks something like this:

const signInWithGoogle = () => {
    const provider = new GoogleAuthProvider();

    signInWithPopup(auth, provider)
      .then((result) => {})
      .catch((error) => {
        const errorMessage = error.message;
        console.log("Google login encountered error:");
        console.log(errorMessage);
      });
};

This seems to work just fine - I can log in and console log user info, as well as log out and confirm auth.currentUser is null. It just seems like the code in useEffect() runs before currentUser is populated.

Any thoughts on how to get around this? Or maybe a better way to check for authentication on page load?

Upvotes: 1

Views: 108

Answers (1)

Sathi Aiswarya
Sathi Aiswarya

Reputation: 2905

Answering this as community wiki.As mentioned above in comments by Mises

The onAuthStateChanged() observer is triggered on sign-in or sign-out.Set an authentication state observer and get user data

For each of your app's pages that need information about the signed-in user, attach an observer to the global authentication object. This observer gets called whenever the user's sign-in state changes.

Attach the observer using the onAuthStateChanged method. When a user successfully signs in, you can get information about the user in the observer.

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Upvotes: 1

Related Questions