get data from all documents in an collection firebase firestore

Tags: , , , ,



i need to get the data of all the documents of a collection in the firestore.

but in my forEach I am getting only the first document and I have two.

he prints the console twice but in my setPoints state he puts only the first

what I am doing wrong??

const db = firestore();

        await db
          .collection('Providers')
          .get()
          .then(snapshot => {
            if (snapshot.empty) {
              console.log('nao tem');
              return;
            }

            snapshot.docs.forEach(item => {
              console.log('item', item.data());

              setPoints([
                ...points,
                {
                  id: item.id,
                  latitude: item.data().address.latitude,
                  longitude: item.data().address.longitude,
                },
              ]);
            });

Answer

I don’t immediately see what’s going wrong in your code. But this seems a bit more concise and idiomatic, so it may be worth a shot:

const db = firestore();

await db
  .collection('Providers')
  .get()
  .then(snapshot => {
    if (snapshot.empty) {
      return;
    }

    let points = snapshot.docs.map(item => {
        return {
          id: item.id,
          latitude: item.data().address.latitude,
          longitude: item.data().address.longitude,
        },
      ]);
    });

    setPoints(points);
  })


Source: stackoverflow