0
votes

I have a user profile that pulls the user's data from a firestore document. The document returns the data as expected, however, in the console I get 8 identical errors that suggest that the data is undefined.

My code for retrieving the user data is as follows:

TS:

export class UserProfileComponent implements OnInit {
  activeUserID: string;
  userRef: AngularFirestoreDocument<User>;
  userData;

  constructor(public afAuth: AngularFireAuth, private db: AngularFirestore) {
    this.getActiveUser();
  }

  ngOnInit() {

  }

  async getActiveUser(){
    const user = await this.afAuth.currentUser;
    this.activeUserID = user.uid;
    this.getUserId();
    this.getUserData();
  }

  getUserId(){
    this.userRef = this.db.collection('users').doc(this.activeUserID);
  }

  getUserData(){
    this.db.collection('users').doc(this.activeUserID).ref.get().then((doc) => {
      this.userData = doc.data();
    });
  }
}

HTML:

<div class="col-md-5">
  <h2>{{userData.displayName}}</h2>
  <h6>{{userData.username}}</h6>
  <p>This is a description about the user.</p>
</div>

Also, if I console.log the userData, it returns undefined depending where it is output.

Screenshot of the console:

core.js:6228 ERROR TypeError: Cannot read property 'displayName' of undefined
    at UserProfileComponent_Template (user-profile.component.html:10)
    at executeTemplate (core.js:12156)
    at refreshView (core.js:11995)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)
    at refreshView (core.js:12051)
    at refreshEmbeddedViews (core.js:13391)
    at refreshView (core.js:12022)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)
1
It's better to copy error message text into the question itself rather than showing screenshots. That makes it easier to read, copy, and search.Doug Stevenson
@DougStevenson - thanks for the suggestion, I've updated the questionPeterL1995

1 Answers

2
votes

The TypeScript signature for doc.data() suggests that it can return undefined. This happens when there is no document at the location of your query. Since Firestore doesn't make any guarantees about the existence of a document at the time of a query, you should check to see if the document data exists before using it.

That error message is TypeScript specifically telling you that you're trying to reference a property on an object could, in fact, be undefined, which leads to crashes. You should check to see if it has an object value before using it, and also decide what you want to do if it doesn't exist.

this.db.collection('users').doc(this.activeUserID).ref.get().then((doc) => {
  const data = doc.data();
  if (data) {
    // in this block, TypeScript guarantees you that data will have an object value
    this.userData = data;
  }
  else {
    // what do you want to do if it doesn't exist?
  }
});