【问题标题】:Cleaning up a snapshot with firestore使用 Firestore 清理快照
【发布时间】:2021-11-24 08:47:43
【问题描述】:

我目前正在为我的 BAAS 使用 firestore/firebase,并且正在努力从集合中获取一些数据。我有数据渲染和通信正常但是我不知道如何正确清理我的效果挂钩。

我读到 firestore 有一个内置的方法来使用 onsnapshot 功能,但我无法弄清楚。

这是对 firestore 数据库的实际 API 调用:

  getBuds: async (uid) => {
    try {
      const snapshot = await db
        .collection('users')
        .doc(uid)
        .collection('buds')
        .get();
      return snapshot.docs.map((doc) => doc.data());
    } catch (error) {
      console.log('Error @getBuds ', error);
    }
  },

这是调用它的效果函数:

useEffect(() => {
    firebase
      .getBuds(user.uid)
      .then((res) => setBuds(res))
      .catch((err) => console.log(err));
  }, [buds]);

请帮我清理一下!!!我会很感激的

更新** 因此,我使用 onsnapshot 函数修改了原始代码,并设法从火存储中提取我想要的数据,我正在获取每个文档并使用此代码将每个文档推送到一个数组中。但是我现在似乎无法将此代码放入我调用“getBuds”方法的组件中:(

这是更新后的 getBuds:

getBuds: async (uid) => {
    let unsubscribe;

    try {
      const budData = [];

      unsubscribe = await db
        .collection('users')
        .doc(uid)
        .collection('buds')
        .onSnapshot((snapshot) => {
          snapshot.forEach((doc) => {
            budData.push(doc.data());
          });
          console.log(budData);
          return budData;
        });
    } catch (error) {
      console.log('Error @getBuds ', error);
    }
  },

【问题讨论】:

    标签: javascript firebase google-cloud-firestore use-effect


    【解决方案1】:

    您可以使用onSnapshot 监听器的取消订阅方法:

    let unsubscribe;
    
    getRealtimeUpdates = function(document) {
            unsubscribe = firestore.collection("collection_name")
                .onSnapshot(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    if (doc && doc.exists) {
                        const myData = doc.data();
                        // DO SOMETHING
                    }
                });
            });
        }
      
      // unsubscribe:
      
      unsubscribe();
    

    更多信息请关注Firestore unsubscribe to updates

    【讨论】:

    • OP 没有使用监听器。
    • 那就没什么好清理的了。
    • 我已经尝试使用 onSnapshot 方法,但似乎无法让它正确返回数据,而不是我上面的数据。您能否更具体地说明如何进入我上面的代码?
    • 可以参考这个链接:stackoverflow.com/questions/56450975/… 有用吗?
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    相关资源
    最近更新 更多