0

I want to run a function that requires user id. But the function runs before getAuth is finished.

const user = getAuth()
getDoc(doc(db, 'users', user.currentUser.uid))

This is what I want to run and it gives an error saying that user.currentUser.uid is undefined.

What should I do to run the function after getting the uid?

React version: 18.2.0

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

1

getAuth() is synchronous, so that is not the problem. The problem is that there is no current user, so your user.currentUser returns undefined and you can't call .uid on that.

If this code runs when the app/page loads, it might be that Firebase is still restoring the user state, which requires it to call to the server (to check a.o. if the account was suspected) and is an asynchronous operation for that reason. If this is the case, you'll want to use an auth state listener as shown in first code snippet in the documentation on getting the current user:

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;
    getDoc(doc(db, 'users', uid))
    // ...
  } else {
    // User is signed out
    // ...
  }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807