1
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

2
  • 3
    Firestore returns a Promise, which is being resolved after the setState is called. blog.sessionstack.com/… Commented Dec 4, 2020 at 13:38
  • 1
    You will need to setState only after all the queries are complete, which means you wil need to change the structure of this code to use promises correctly. Commented Dec 4, 2020 at 16:42

1 Answer 1

3
 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.

Sign up to request clarification or add additional context in comments.

4 Comments

That actually still won't work because the forEach loop does not know to await the results of each iteration. What you've written will log an empty array and not wait for each query to complete.
I use for-of loops instead of .forEach() when I have sequential async work for this reason.
You can also use Promise.all(arrayOfIds.map(...etc...) just to wait for the resulting array of promises to resolve.
@DougStevenson you're right, my bad. I will edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.