I am trying to make the changes in real time using nextjs and firebase firestore. However I do need to reload yet in order for me to see the changes.
const [getUsers, setUsers] = useState("");
const checkStatus = async (collectionName, valueFieldName, setterName) => {
const q = query(
collection(db, collectionName),
where("isVerified", "==", valueFieldName)
);
const snapshot = await getCountFromServer(q);
setterName(snapshot.data().count);
};
and I am calling the function in the body using parameters
checkStatus("users", "false", setUsers);
and I am trying to display it by
<h1> user counter in realtime: {getUsers} </h1>
2
Answers
You need to listen to updates from Firebase Firestore to update the state in real-time without needing to reload the page. For that you should use
onSnapshot
which listens in real time which allows you to update your application’s state and UI in real-time without needing to refresh the page.Here’s one example:
If you don’t need real-time updates of the count, you can use the
getCountFromServer()
method instead of theonSnapshot()
method to retrieve the count once the component mounts. Example for that:Reference taken from:
Count documents in Firestore Collection
,onSnapshot
Firestore’s COUNT() queries currently don’t support realtime updates. From the documentation on its limitations:
So you will indeed either have to reload the page, or set up some client-side refresh mechanism to get the latest value from the server.