Cannot read property uid of undefined

How many times have you seen that error message? (Be honest!).

I’ve seen it so many times (both on the console and my inbox) that I lost track of the exact number, but it’s probably embarrassingly high.

Today we’re going to go through why that error happens and the two things you need to keep in mind to never see it again.

Why does the user return as undefined (or even null)?

You know there’s a logged in user, you just logged in, heck, you can even see the user object in chrome dev tools.

Then why is it still returning undefined? There’s a straight answer to it. You’re fetching the user object BEFORE that object is ready to be used.

Now, this can happen because of several different reasons, but if you follow this “rule” you won’t see that error again.

Make it an Observable

We can make the user call asynchronous by subscribing to the auth observable instead.

So depending on the library you’re using, the JavaScript SDK has onAuthStateChanged() and AngularFire has authState().

Instead of fetching the user synchronously, we can do:

// For AngularFire:
import { authState, Auth } from '@angular/fire/auth';

constructor(private readonly auth: Auth) {}

authState(this.auth).subscribe( user =>; {
  if (user) { this.userId = user.uid }
});


// For the JS SDK
import { getAuth, onAuthStateChanged } from 'firebase/firestore';

const auth = getAuth();

onAuthStateChanged(auth, (user) =>; {
  if (user) { this.userId = user.uid }
});

That way, Ionic makes an asynchronous request to Firebase and ensures that it will have the user before trying to use its properties.

If you keep those two rules in mind whenever you’re dealing with auth states, you won’t have to worry about that annoying error again :)