Septias
Septias

Reputation: 33

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

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?

Upvotes: 3

Views: 697

Answers (3)

Ivan Lopes
Ivan Lopes

Reputation: 168

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

Upvotes: 2

Axnyff
Axnyff

Reputation: 9964

They are not the same. The first when simply means that your object has a forEach method.

The second one means that your object has a [Symbol.iterator] property which is a generator. This makes your object iterable.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator

Upvotes: 0

Alberto Rivera
Alberto Rivera

Reputation: 3752

A querySnapshot, which is what is returned from the get method, is not an array or an iterable.

https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot

forEach is a method from the querySnapshot object, which is why you can use it.

Upvotes: 4

Related Questions