亲爱的, 请告诉我如何保存 Firestore 请求的输出(请阅读下面代码中的评论):
const firestore = firebase.firestore();
export const fetchedTickets = []; //I want to store the fetched tickets from a collection "tickets" and use it somewhere else
//Starting to listen changes in Tickets collection
const unsubscriberForTicketsListener = firestore
.collection("tickets")
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
// console.log("Added Ticket: ", change.doc.data());
fetchedTickets.push(change.doc.data());
}
if (change.type === "modified") {
console.log("Edited Ticket: ", change.doc.data());
}
if (change.type === "removed") {
console.log("Remvoed Ticket: ", change.doc.data());
}
});
console.log(fetchedTickets) //From here, I can reach the fetched tickets, but I can't return this array, or do something valuable with it (store, for example)
});
console.log(fetchedTickets) //Here, fetchedTickets is just an empty array, so I can't return it's value to use it in a different file, for example
答案 0 :(得分:0)
这是预期的行为。由于数据是从 Firestore 异步加载的,所有需要数据的代码都需要在回调中(就像你的第一个 console.log(fetchedTickets)
)是。
虽然回调之外的代码可以访问相同的变量,但它通常在加载数据之前运行 - 除非您自己确保它在正确的时间运行(通过使用 Promise 或类似 RxJS 的东西)。
另见:
还有更多来自search的内容。