[英]How can I map data from a firestore database in a useEffect hook
I'm trying to get some data from a firestore database and save it into a array in react.我正在尝试从 firestore 数据库中获取一些数据并将其保存到一个数组中进行反应。 This is my code.
这是我的代码。
const readDocuments = async () => {
const allData = await getDocs(collectionRef);
//console.log(allData);
// allData.forEach((doc) => {
// console.log(doc.id, " => ", doc.data());
// });
setData(allData.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(data);
//return allData;
};
When I check the console, this is what I get.当我检查控制台时,这就是我得到的。
Not really sure what I'm doing wrong here.不太确定我在这里做错了什么。 I saw pretty much the same method used in a tutorial.
我在教程中看到了几乎相同的方法。 And if I uncomment the foreach loop within the function, it outputs the data properly so I figure it's not a issue with actually retrieving the information.
如果我取消注释 function 中的 foreach 循环,它会正确输出数据,所以我认为这不是实际检索信息的问题。
Edit: The function above is nested in a useEffect hook.编辑:上面的 function 嵌套在 useEffect 挂钩中。
import { useEffect, useState } from "react";
import { collection, getDocs } from "firebase/firestore";
import { db } from "../firebase/config";
const useGetDocs = (collectionName) => {
const [documents, setDocuments] = useState([]);
//Firebase Collection Reference
const postCollectionRef = collection(db, collectionName);
useEffect(() => {
const getDocuments = async () => {
const data = await getDocs(postCollectionRef);
setDocuments(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
};
getDocuments();
}, []);
return { documents };
}
export default useGetDocs;
This is the full file that I used and it works now.这是我使用的完整文件,现在可以使用了。 Not necessarily sure what was wrong before but the main change I made was created it as a custom hook using the 'use' keyword which might have had something to do with it.
不一定确定之前出了什么问题,但我所做的主要更改是使用“use”关键字将其创建为自定义挂钩,这可能与它有关。 I'm no expert by any means and could still be doing something wrong but hopefully this helps someone if they have a similar issue.
我无论如何都不是专家,仍然可能做错事,但希望这对遇到类似问题的人有所帮助。
Cheers!干杯!
if you look at the documentation they are showing you exactly how to do it.如果您查看文档,他们会向您展示具体操作方法。
import { collection, query, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.