0

Im having trouble accessing items in an array after pushing data into it from Firebase.

const rootref = firebase.firestore().collection("Projects");
const projectList = []
rootref.get().then(function(querySnapshot){
  querySnapshot.forEach(function(doc) {
    projectList.push(doc.data())
  });
});

//this returns all items in the list
console.log(projectList)
//this returns null
console.log(projectList[0]);

bns2000
  • 1
  • 1
  • The issue is accessing individual elements in the array. The entire array is returned just fine. – bns2000 May 30 '21 at 02:02
  • Look at the answer that was linked above. It is important you understand the order your code is running/executing in. As written, the async operation causes 1) The REFERRENCED array is logged 2) The first (non-extant) items in the (then empty) array is logged, ONLY THEN 3) Items begin to be pushed into the array. You can demonstrate this to yourself by adding log statements adjacent to the push operations. – Chase May 30 '21 at 02:29
  • The fact that the entire array seems to work is just Chrome playing tricks on you, by "helpfully" updating the array in the console when it is updated by the callback. The cause is really the asynchronous nature of the callback. – Frank van Puffelen May 30 '21 at 03:16

0 Answers0