skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search