Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase get 2 subcollections count caching

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading