'How to fix the useEffect won't update unless refresh
//real time database listner :
const getJobStatusSnapshot = ()=> {
const que = query(jobsCollectionRef, where("auth_ID", "==", user.uid))
const unsubscribe = onSnapshot(que, (querySnapshot) => {
const temp = [];
querySnapshot.forEach((doc) => {
// cities.push(doc.data());
temp.push({...doc.data(), id:doc.id})
// console.log({...doc.data(), id:doc.id})
setJobDoc(temp)
});
})
unsubscribe();
}
useEffect(()=>{
getJobStatusSnapshot()
},[])
Sometime it doesn't retrieve the data. I tried to pass [jobDoc]. But it gives me the same results. And then suddenly returns bunch of errors. Also, I noticed that if I wanna retrieve the data first time, I have to comment out > unsubscribe()
Solution 1:[1]
if you set your useEffect dependencies to [jobDoc] it will be trigger on mount and on jobDoc value update which happen inside setJobDoc(temp), so it will be infinite loop which give you a bunch of errors. So if you only provide that code, I think you should listen to [user] or [user.uid]. Everytime the user or user.uid change it will rerun the getJobStatusSnapshot.
useEffect(()=>{
getJobStatusSnapshot()
},[user])
Solution 2:[2]
You are setting [] as dependency in useEffect, that means it only will perform that action when loading the page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Yappeter |
| Solution 2 | MaiGoL7 |
