0

I'm trying to get data from firestore database and using *ngFor directive to display the data in Ionic 4. When I check the console, it shows an error TypeError: Cannot read property 'todoList' of undefined. Need help.

todo.ts

ngOnInit(): void {
   const todoList= [];
   var userid = this.afAuth.auth.currentUser;
   var getid = userid.uid;
   console.log(getid);

   this.afs.firestore.collection('todos')
   .where('userID', '==', getid)
   .get()
   .then(function(querySnapshot){
     querySnapshot.forEach(doc=>{
        console.log(doc.id, "=>", doc.data());
        this.todoList.push({
          id: doc.id,
          Title: doc.data().title,
          Description: doc.data().desc,
        })
     });
   }).catch(function(error){
     console.log(error);
   })
 }

At this point, I'm not sure what I did wrong.

todo.html

  <div *ngFor="let todo of todoList">

    <div class="user">
      <span> {{ todo.Title }} </span>

      <p>{{ todo.Description }}</p>
    </div>
  </div>

The 'todo.html` page is blank.

Sleek
  • 3
  • 2

1 Answers1

1

You are 'losing' the this context of the class by using the function keyword. You are better of always using the arrow notation () => {}

// ...
.then((querySnapshot) => {
  // ...
  this.todoList.push({
    id: doc.id,
    Title: doc.data().title,
    Description: doc.data().desc,
  })
})
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • Hi, you are right. I wasn't aware that using `regular function` and `arrow function` gives different result. I always thought both `function` works in similar manner. I need further research on that part. Thank you. – Sleek Oct 29 '19 at 23:39