[英]how can i change the data inside the snapshot on firebase
On my project, I create a function to get the data from firebase and then return it but I always get an empty array this my function below在我的项目中,我创建了一个 function 以从 firebase 获取数据然后返回它,但我总是得到一个空数组,我的 function 下面
export const pullDataFromFirebase = (collectionName, reducerName) => {
let data = []
onSnapshot(collection(db, collectionName), (snapshot) => {
snapshot.docs.map((doc)=>{
data.push(doc.data())
})
})
return data
}
You can't mix the use of promises with Firestore realtime updates.您不能将承诺与 Firestore 实时更新混合使用。 Functions that return a promise ( async
function) are meant to return a single result asynchronously.返回 promise 的函数( async
函数)旨在异步返回单个结果。 onSnapshot
does not return a promise. Instead, it invokes the provided callback whenever the results of the query change. onSnapshot
不会返回 promise。相反,只要查询结果发生变化,它就会调用提供的回调。
If you just want to get the data from the Firestore, you can do this instead:如果您只想从 Firestore 获取数据,您可以改为这样做:
export const pullDataFromFirebase = async (collectionName, reducerName) => {
const q = query(collection(db, collectionName));
const querySnapshot = await getDocs(q);
const documents = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
return documents;
}
to access it, you must call the async function and use the .then
method.要访问它,您必须调用异步 function 并使用.then
方法。 See code below:请参阅下面的代码:
pullDataFromFirebase(collectionName)
.then((data) => {
console.log(data);
});
To listen to changes between snapshots, you can use the sample code from these documentation :要收听快照之间的变化,您可以使用这些文档中的示例代码:
export const pullDataFromFirebase = async (collectionName, reducerName) => {
onSnapshot(collection(db, collectionName), (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log("Added", change.doc.id, change.doc.data());
//call a function.
}
if (change.type === "modified") {
console.log("Modified", change.doc.id, change.doc.data());
//call an function.
}
if (change.type === "removed") {
console.log("Removed", change.doc.id, change.doc.data());
//call a function
}
});
});
}
You could also use React Hooks
, if you prefer.如果愿意,您也可以使用React Hooks
。 By using useState()
and useEffect()
.通过使用useState()
和useEffect()
。 See code below:请参阅下面的代码:
const [data, setData] = useState([]);
async function pullDataFromFirebase(collectionName, reducerName) {
const colRef = query(collection(db, collectionName))
onSnapshot(colRef, (snapshot) => {
setData(snapshot.docs.map(doc => ({
doc.data()
})))
})
}
useEffect(() => {
pullDataFromFirebase();
},[])
The code above will be able to set your document's data to the state and be able to use it on another function.上面的代码将能够将您的文档数据设置为 state,并能够在另一个 function 上使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.