Home > Mobile >  getAuth() return a object but uid return null when page reload
getAuth() return a object but uid return null when page reload

Time:12-14

My code is so vast; I just put a part of code that I think is essential.

import {getAuth} from "firebase/auth"

const authFirebase = getAuth()
console.log(authFirebase)

const Home = () => {
  ...
  return(
   ...
  )
}

Whenever I reload page (F5) if I just.

console.log(authFirebase)

I retrieved an object that contains uid in the currentUser property, but when I code like this.

 console.log(authFirebase.currentUser.uid)

I got this error

TypeError: Cannot read properties of null (reading 'uid')

I'm so confused; I didn't understand something about Firebase?

CodePudding user response:

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
    // ...
  }
});

CodePudding user response:

the reason is You’re fetching the user object before that object is ready to be used.

You need to wrap that in a condition if it exists then do log to console.

One more way is to add an observer like onAuthStateChanged this will resolve this problem of prefetching the object.

firebase.auth().onAuthStateChanged( user =>; {
  if (user) { console.log(user) }
});
  • Related