Reputation: 63
The response from a Firestore onSnapshot is 2 records which I push into an array named shop.
this.db.collection("Countries").doc("AU")
.collection("cPostcode").doc(this.searchby)
.collection(this.shop).where(how, '==', true)
.onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
shop.push(doc.data());
})
});
console.log('shop.length', shop.length, 'Shop', shop);
if (shop.length) {
this.shopList = shop; .........
I use shop.length > 0
to know if any data is returned, but even though there are 2 items in the array, shop.length
equals to 0.
Output from the console log shows length:2
-
shop.length 0 shop []
0:{ABN: "1", ACN: "2"}
1:{ABN: "3", ACN: "4"}
length:2
__proto__:Array(0)
I have tried putting a flag in the forEach, but it goes out of scope so does the "this.count" variable I tried. I have been working on this on and off for days. I have googled this problem and general Typescript help, but no one else seems to have this problem. What am I doing wrong?
Upvotes: 1
Views: 531
Reputation: 250832
To reliably get the length, you need to make sure you wait for a result.
this.db.collection("Countries").doc("AU")
.collection("cPostcode").doc(this.searchby)
.collection(this.shop).where(how, '==', true)
.onSnapshot((querySnapshot) => {
// In here, we have data
querySnapshot.forEach((doc) => {
shop.push(doc.data());
});
console.log('shop.length', shop.length, 'Shop', shop);
// Therefore, shop.length should work _reliably_
if (shop.length) {
alert(shop.length);
}
});
Alternatives include using promises, or calling a function when you have the result (rather than just chucking all the code inside that callback function).
Upvotes: 1