I am learning ReactJS and I am a beginner.
I am trying to get the real-time data change from firebase firestore.
useEffect(() => {
getValues();
});
const q = query(collection(db, "users"));
const getValues = onSnapshot(q, (querySnapshot) => {
const updateUser = [];
querySnapshot.forEach((doc) => {
updateUser.push(doc.data());
});
setUsers([...updateUser]);
});
Thanks for helping.
The getValues() will actually unsubscribe from the listener. onSnapshot returns a function that can be used to stop the listener which is getValues in this case. Try refactoring your code to:
useState(() => {
const q = query(collection(db, "users"));
onSnapshot(q, (querySnapshot) => {
const updateUser = [];
querySnapshot.forEach((doc) => {
updateUser.push(doc.data());
});
setUsers([...updateUser]);
});
}, [])