Home > other >  Why isn't doc.data() a function in this if-statement?
Why isn't doc.data() a function in this if-statement?

Time:03-21

When I remove the if-stament I get the data and doc.data() works, but I need to check for type 'added' so I don't output existing data again and again.

With the if-statement, I get this error message:

Uncaught TypeError: doc.data is not a function

 async getChats(callback){
    const roomFilter = query(colRef, where("room", "==", this.room));
    const ordered = query(roomFilter, orderBy('created_at'));
    this.unsub = onSnapshot(ordered, (snapshot) => {
      let items = []
      snapshot.docChanges().forEach(doc => {
        if(doc.type === 'added'){
          items.push({ ...doc.data(), id: doc.id })
          console.log(items);
          callback(items);
      }})    
    });

CodePudding user response:

snapshot.docChanges().forEach(doc => {

The variable you've called doc is more than just the document. It has additional information about the change. With the variable name you've chosen you need to do:

items.push({ ...doc.doc.data(), id: doc.doc.id })

I'd consider renaming it though, maybe to "change"

snapshot.docChanges().forEach(change => {
  if (change.type === 'added') {
    items.push({ ...change.doc.data(), id: change.doc.id })
    console.log(items);
    callback(items);
  }
})
  • Related