2

I can't access the contents of an array I saved from a firestore snapshot.

Here is the code:

function getDataFromFirestore() {
  let myList = [];
  db.collection("test")
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        myList.push(doc.data());
      });
    });

  console.log(myList);
  console.log(myList[1]);
  console.log(myList.length);
}

getDataFromFirestore();

here is return of console.log():

result of console.log()

Questions: Why were 3 items saved in the array using forEach and the length of it is = 0?

How do I access the objects saved in the array?

Thank you very much for your help.

1
  • I have another doubt, if I move the array myList[] outside of the function, I can read and get data from this array to use in another function? Commented Mar 9, 2021 at 19:34

1 Answer 1

2

db.collection("test").get() returns a promise, which means that is executed after the console.logs at the end.

A solution could be to move the console.logs inside then, or to use async await.

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

Comments

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.