Not Able To Iterate Over Array Of Users Pulled From Firebase
Solution 1:
Data is loaded from Firestore asynchronously. Since this may take some time, your main code will continue to run while the data is loading. Then when the data is loaded, your callback functions is called.
You can easily see this in practice by adding some logging:
console.log("Before starting onSnapshot");
db.collection("Users").onSnapshot(res => {
console.log("Got data");
});
console.log("After starting onSnapshot");
When you run this code, it logs:
Before starting onSnapshot
After starting onSnapshot
Got data
This is probably not the order you expected, but it completely explains why the log statements don't work as you expected. By the time you log the array length, the data hasn't been loaded from the database yet.
The reason logging the array does seem to work, is that Chrome updates the log output after the data has loaded. If you change it to console.log(JSON.stringify(temp));
, you'll see that it logs an empty array.
This means that all code that needs access to the data, must be inside the callback, or be called from there:
let temp = [];
db.collection("Users").onSnapshot(res => {
const changes = res.docChanges();
changes.forEach(change => {
if (change.type === "added") {
temp.push({
id: change.doc.id,
email: change.doc.data().email
});
}
});
console.log(temp);
console.log(temp.length);
});
As you can probably imagine, many developers who are new to asynchronous APIs run into this problem. I recommend studying some of the previous questions on this topic, such as:
Post a Comment for "Not Able To Iterate Over Array Of Users Pulled From Firebase"