Search code examples
firebaseionic4

Cannot read property 'uid' of null when logout


Every time I logout from my app, I get

Cannot read property 'uid' of null

from console. it leads reference to below code:

constructor( private firestore: AngularFirestore, private auth: AuthService, ) 
{
firebase.auth().onAuthStateChanged(user => {
  if (this.currentUser == user) {
    this.currentUser = firebase.auth().currentUser;
    this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`);
  }
});

Solution

  • The onAuthStateChanged callback will fire whenever the user's authentication state changes, so whenever they sign in, or they're signed out. In the latter case, the user will be null, which you don't handle correctly in your code right now.

    This looks more correct:

    firebase.auth().onAuthStateChanged(user => {
      this.currentUser = firebase.auth().currentUser;
      if (this.currentUser) {
        this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`);
      }
    });