Debugger
Debugger

Reputation: 21

Cannot read property of 'uid' of null

I need help, I used firebase as back-end and Ionic 4 as front-end.

I have error on console where when I first open/lunch the app, I received Cannot read property of 'uid' of null on console.

I read some related solutions but I haven't found one that solves my problem.

Below is the code when I implemented it in my app:

initializeApp() {

this.afAuth.auth.onAuthStateChanged(user => {
  const userId = user.uid;
  this.db.doc(`accounts/${userId}`).valueChanges().pipe(
    take(1)
  ).subscribe(userData => {
    const role = userData['role'];
    if (role == 'USER') {
      console.log('we got a customer user');
      this.router.navigateByUrl('/tabs/home')
    } else if (role == 'VENDOR') {
      console.log('we got a seller user');
      this.router.navigateByUrl('/vendor-tabs/home-vendor')
    }
  })
})
}

Upvotes: 0

Views: 72

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317362

An auth state change listener is called when a user is either signed in and signed out. user will be null if not signed in. This means you have to check if user is truthy before you start accessing properties on it.

this.afAuth.auth.onAuthStateChanged(user => {
  if (user) {
    // user is signed in
    const userId = user.uid;
  }
  else {
    // user is signed out - can't use properties of user.
  }
}

See the API documentation.

Upvotes: 1

Debugger
Debugger

Reputation: 21

This is what I did to get rid of the cannot read property of 'uid' null.

this.afAuth.auth.onAuthStateChanged(user => {
  if (user) {
    const userId = user.uid;
    this.db.doc(`accounts/${userId}`).valueChanges().pipe(
      take(1)
    ).subscribe(userData => {
      const role = userData['role'];
      if (role == 'USER') {
        console.log('we got a customer user');
        this.router.navigateByUrl('/tabs/home')
      } else if (role == 'VENDOR') {
        console.log('we got a seller user');
        this.router.navigateByUrl('/vendor-tabs/home-vendor')
      }
    })
  } else {
    return of(null);
  }
})

Upvotes: 0

Related Questions