Home > Software engineering >  Firestore getCountFromServer not real time updating?
Firestore getCountFromServer not real time updating?

Time:02-04

I am using the getCountFromServer() for my React App to display the number of docs in a collection. However, when the user deletes a doc on the front end or creates one, the count is not updated in real-time. Is it possible to fix this or must the user always reload the page to see the latest data?

CodePudding user response:

The documentation says, emphasis mine:

count() aggregation queries are currently only supported via direct server response. Queries are served only by the Cloud Firestore backend, skipping the local cache and any buffered updates. This behavior is identical to operations performed inside Cloud Firestore transactions. You cannot currently use count() queries with real-time listeners and offline queries.

So, no, you can't get realtime count updates. You will have to make the request again to get an update. Whether or not you require a page refresh is up to you.

CodePudding user response:

As @DougStevenson mentioned in his comment, there is no way you can get real-time updates when you're using count(). It's true you can call count() every time it is needed, but there is however a workaround.

To solve this, you should consider storing a counter in a document at a known path, and then increment its value every time a new document is added or decrement the value every time a document is deleted. To get real-time updates, simply attach a persistent listener on that document and you'll be up to date with the number of documents in the collection.

Besides that, if your collection grows in size (> 10,000,000 documents), then the above solution might be the only solution you have. For that, please check @FrankvanPuffelen's answer from the following post:

CodePudding user response:

If you are using getCountFromServer() to load the initial count and then want to decrement it for all active users when a document is deleted, you can use a listener on the same collection and update the state on frontend like this:

import { collection, query, where, onSnapshot } from "firebase/firestore";

// initial state loaded by getCountFromServer()
const [count, setCount] = useState(10);

const q = query(collection(db, "collectionName"));

const unsubscribe = onSnapshot(q, (snapshot) => {
  snapshot.docChanges().forEach((change) => {
    if (change.type === "removed") {
        console.log("Removed document: ", change.doc.data());
        // TODO: Decrement the count in state
        // e.g. setCount(count - 1)
    }
  });
});

This way you won't have to calculate the count again or maintain the count anywhere.

  • Related