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

Firestore query onSnapshot is returning me all previous docs on each change

I am adding docs to a collection of messages. For getting real time updates in my UI, I am listening to new docs that have been created after "new Date()".

The thing is that, after getting the first snapshot with all the documents that match the query, when a new doc is added, I am receiving all the previous detected docs in the listener.

Is this the expected behavior?? What am I doing wrong?

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

This is what I am doing:

    export function listenNonDeletedChatMessages(
      chatRoomId,
      startAt = undefined,
      onMessageReceived = undefined,
      onNext = undefined,
      onError = undefined
    ) {
      const currentUser = getCurrentUser();
    
      if (!currentUser) {
        throw authErrors.authenticationRequired();
      }
    
      let query = firestore
        .collection("chats")
        .doc(chatRoomId)
        .collection("messages")
        .where("content.deletedAt", "==", null)
        .orderBy("date");
    
      if (startAt) {
        query = query.startAt(startAt);
      }
    
      return query.onSnapshot(handleChanges, onError);
    
      function handleChanges(querySnapshot) {
        const messages = [];
    
        querySnapshot.docs.forEach((doc) => { // I am getting N docs on each change, why? 
          const messageData = {
            id: doc.id,
            ...doc.data(),
          };
    
          const parsedMessage = parseChatMessage(
            messageData,
            currentUser.uid
          );
    
          console.log(messageData); <--- this method is logging me all the already detected docs!
    
          messages.unshift(parsedMessage);
    
          onMessageReceived?.(parsedMessage);
        });
    
        querySnapshot.docChanges().forEach((change) => { // 1 change detected, as expected
          console.log(change.type); <--- THIS ONLY LOGS "added" one time when a doc is added!
        });
    
        onNext?.(messages);
      }
    }

Note: I am not talking about the initial status, where all docs are fetched, I am saying that I am receving the same docs again and again on any new doc addition, while they are not being modified.

>Solution :

That is the expected behavior: the QuerySnapshot contains information about all documents that match the query, not just about the changes.

If you want to process all documents, loop over docs as you do first in your code.

If you want to process only the changes, loop over docChanges as you do later in your code.

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