I do need to reload yet in order for me to see the changes.
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:
import { collection, onSnapshot, query, where } from "firebase/firestore";
import { db } from "@/firebase/firebaseConfig";
import React, { useEffect, useState } from "react";
export default function snapshot() {
const [userCount, setUserCount] = useState(0);
const checkStatus = (
collectionName: string,
valueFieldName: boolean,
setterName: React.Dispatch<React.SetStateAction<number>>
) => {
const q = query(
collection(db, collectionName),
where("isVerified", "==", valueFieldName)
);
const unsubscribe = onSnapshot(q, (snapshot) => {
const count = snapshot.size;
setterName(count);
});
return unsubscribe;
};
useEffect(() => {
const unsubscribe = checkStatus("users", false, setUserCount);
return () => {
unsubscribe();
};
}, []);
return (
<div>
<h1>User Count: {userCount}</h1>
</div>
);
}
If you don't need real-time updates of the count, you can use the getCountFromServer()
method instead of the onSnapshot()
method to retrieve the count once the component mounts. Example for that:
import { collection, getCountFromServer, query, where } from "firebase/firestore";
import { db } from "@/firebase/firebaseConfig";
import React, { useEffect, useState } from "react";
export default function Home() {
const [userCount, setUserCount] = useState(0);
const checkStatus = async (
collectionName: string,
valueFieldName: boolean,
setterName: React.Dispatch<React.SetStateAction<number>>
) => {
const q = query(
collection(db, collectionName),
where("isVerified", "==", valueFieldName)
);
const snapshot = await getCountFromServer(q);
const count = snapshot.data().count;
setterName(count);
};
useEffect(() => {
checkStatus("users", false, setUserCount);
}, []);
return (
<div>
<h1>User Count: {userCount}</h1>
</div>
);
}
Reference taken from: Count documents in Firestore Collection
,
onSnapshot