I have a firestore collection, and I want to return the entire thing, however I am currently only returning one item. My intuition is that because my resolve function is in the forEach it is only returning the last item it sees, however when I move it outside of the forEach my data comes back undefined
Here is what I have written:
componentDidMount() {
this.getItemsPromise().then((data) => {
this.setState({ data: data })
});
}
getItemsPromise() {
return new Promise((resolve, reject) => {
this.cancelPromise = reject;
const db = firebase.firestore();
db.collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const data = [];
data.push(doc.data())
resolve(data);
});
});
});
}
Try this. It's better you don't use const for editable array data. and you should place resolve outside of forEach so resolve not triggered in first loop.
getItemsPromise() {
return new Promise((resolve, reject) => {
this.cancelPromise = reject;
const db = firebase.firestore();
db.collection("items").get().then(function(querySnapshot) {
let data = [];
querySnapshot.forEach(function(doc) {
data.push(doc.data());
});
resolve(data);
});
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.