P粉8068340592023-08-25 12:43:07
It will be better if you combine useEffect and useState. useEffect is responsible for setting and disabling the listener, and useState is only responsible for the data you need.
const [data, setData] = useState([]); useEffect(() => { const unsubscribe = someFirestoreAPICall().onSnapshot(snap => { const data = snap.docs.map(doc => doc.data()) this.setData(data) }); //记得在卸载组件时取消实时监听器,否则会造成内存泄漏 return () => unsubscribe() }, []);
You can then directly reference "data" in the useState hook in your application.
P粉1655228862023-08-25 12:37:51
A simple useEffect worked for me, i don't need to create a helper function or anything of sorts,
useEffect(() => { const colRef = collection(db, "data") //real time update onSnapshot(colRef, (snapshot) => { snapshot.docs.forEach((doc) => { setTestData((prev) => [...prev, doc.data()]) // console.log("onsnapshot", doc.data()); }) }) }, [])
A simple useEffect works for me, I don't need to create any helper functions or anything like that,
useEffect(() => { const colRef = collection(db, "data") //实时更新 onSnapshot(colRef, (snapshot) => { snapshot.docs.forEach((doc) => { setTestData((prev) => [...prev, doc.data()]) // console.log("onsnapshot", doc.data()); }) }) }, [])