I have a need to refresh in order for the changes to be visible.
To keep your application updated with real-time changes from Firebase Firestore without requiring a page reload, you can utilize the onSnapshot
method. This allows you to listen for updates and update your state and UI instantly without refreshing the page.
Here's an example of how to implement it:
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 real-time updates are not necessary, you can use the getCountFromServer()
method instead of onSnapshot()
to fetch the count when the component mounts. Here's an example:
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>
);
}
References: Count documents in Firestore Collection
,
onSnapshot