Why does for-each work, but for...of... doesn't?

Viewed 369

This is my code to fetch data from firebase:

const querySnapshot = await db.collection('entries').get()

I want to add the data of every entry-element to a new array for which I got two ways to do it:

querySnapshot.forEach((entry) => {
   const entryData = entry.data()
   entries.value.push(entryData)
})

and

for (const entry of querySnapshot) {
      const entryData = entry.data()
      if (entry) { entries.value.push(entryData)
}

The first solution works, but the second throws this error: TypeError: "querySnapshot is not iterable". Aren't the two ways basically doing the same? Why does on throw an error while the other doesn't?

3 Answers

As Alberto Rivera stated, the forEach is a QuerySnaphot method and it does the work for you. But you can loop from those documents yourself by using:

    const entries = await db.collection('entries').get();
    for (entry of entries.docs) {
        console.log(entry.id);
    }

Note that ".docs" comes with your querysnapshot and its is iterable

Related