在Firestore中删除文档不会更新onSnapshot

时间:2018-11-06 04:09:18

标签: react-native google-cloud-firestore

我正在React Native中从Firestore中获取项目列表。

如果项目文档已更新,我的列表将通过onSnapshot刷新。但是,如果文档被删除,我的列表不会刷新。

我有办法捕获已删除的文档吗?

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 个答案:

答案 0 :(得分:0)

尝试以下方法是否对您有用:

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.
            }
        });
    });