Deleting documents in Firestore not updating onSnapshot

Viewed 1884

I am fetching a list of items from firestore in react native.

If an item document is updated, my list refreshes as expected through onSnapshot. But if the document is deleted, my list does not refresh.

Is there a way for me to catch deleted documents?

this.unsubscribe = firebase.firestore().collection('bigItems').doc(id)
                  .collection('littleItems').onSnapshot(this.getItems)

   getItems = (querySnapshot) => {
     const items = [];

    querySnapshot.forEach((doc) => {
      firebase.firestore().collection('events').doc(doc.id).get()
        .then(item => {
            const { id } = item.data();
            items.push({
              id: item.id
            });
            this.setState({
              items: items,
              loading: false,
           });
        })
        .catch(function (err) {
          return err;
        });
    })
  }
1 Answers

Try if the following approach works for you:

const dataRef = firebase.firestore()
            .collection('bigItems').doc(id)
            .collection('littleItems').onSnapshot(res => {

            // Listen to change type here
            res.docChanges().forEach(change => {

            const docName=change.doc.id;
            const docData=change.doc.data();

            // Refer to any field in the document like:
            // E.g. : data.name, data.text etc.
            // i.e. (whatever fields you used for the document)

            if (change.type === "added") {
                // Append to screen
            }
            if (change.type === "removed") {
                // Now, Manually remove from UI
                // Data from state before snapshot is still here,
                // use some reference in data to remove from screen.
            }
        });
    });
Related