H4ypTR0N
H4ypTR0N

Reputation: 25

How to set state after data fetch complete in React

arrayOfIds.forEach((id) => {
      firestore
        .collection("foos")
        .doc(id)
        .get()
        .then((foo) => {
          fooArray.push(foo.data());
        });
    });
console.log(fooArray);
// some output
this.setState({ foos: fooArray });
// but nothing passed to the state

When I console.log fooArray I can see all the data but cant assign it to the state

Upvotes: 1

Views: 86

Answers (1)

Snake Shadow
Snake Shadow

Reputation: 78

 for(let id of arrayOfIds) {
     let foo = await firestore
              .collection("foos")
              .doc(id)
              .get();
     fooArray.push(foo.data());
 }
 console.log(fooArray);
 this.setState({ foos: fooArray });

This would set the state with the correct data - you didnt await the Promise returned by firestore but with this it should work.

Upvotes: 3

Related Questions