Advertisements
In a component in react, I wasnt to display the sum count of two subcollections in a specific document in a collection.
The issue is, each time I go to a different page and go back, the responses seem to refetch and take some time to display (even though the underlying data didn’t change).
Here’s how I’m implementing the count:
const [count, setCount] = useState(null);
const getItemsCount = async () => {
const shelvesCollection = collection(db, "shelves");
const shelfItemsCollection = collection(shelvesCollection, id, "items");
const sliderItemsCollection = collection(shelvesCollection, id, "sliders");
const [shelfSnapshot, sliderSnapshot] = await Promise.all([
getCountFromServer(shelfItemsCollection),
getCountFromServer(sliderItemsCollection),
]);
const shelfCount = shelfSnapshot.data().count;
const sliderCount = sliderSnapshot.data().count;
const totalCount = shelfCount + sliderCount;
setCount(totalCount);
};
useEffect(() => {
getItemsCount();
}, []);
Does this implementation make sense? Or is there a better way? Also, how to enable caching in firebase so that there’s no lag (loading) when rendering the same component again?
>Solution :
The client-side SDKs for Firestore currently don’t cache the count, which is why they’re explicitly called getCountFromServer
.
If you want to avoid the reload delay/cost, consider storing the count in local storage yourself.
You can then either:
- Display the count from the cache right away, and then load it from the server and refresh (if needed). This would mimic the behavior of an
onSnapshot
type listener for regular data. - Determine how old the cached count is and call
getCountFromServer
in case the value is older than you think is reasonable.