首页 > 解决方案 > 在 MobX 中正确同步 Firestore 集合

问题描述

我正在尝试从 MobX 中的 firestore 同步数据,但 onSnapshot 方法有问题。

我正在使用流和生成器来做到这一点。但我不确定如何从 onSnapshot 处理正确的 sub/unsub 监听器

export class MyStore {
  @observable myItems: Array<MyModel> = [];
  sub: any //??

  constructor(){
    this.sync();
  }

  sync = flow(function*(this: MyStore) {
    const dbRef = firestore().collection('items');
    try {
        yield this.sub = dbRef.onSnapshot((data: any)=>{ //??
          // do something with data
          // const items = ...
          this.setItems(items);
        })
    } catch(error) {
      // error handling
    }
  })

  @action setItems = (items: MyModel[]) => {
    this.myItems = items;
  };
}

以及如何纠正退订?还有一个问题——只有第一次同步调用才能捕获错误。当我在 firestore 中更改某些内容时,它会更改 myItems,但它会跳过 try catch 范围(它在 onSnapshot 方法的回调中运行 onlny)。如何“尝试/捕捉”firestore 上的每一个变化?

标签: google-cloud-firestoresynchronizationmobx

解决方案


当你打电话时,onSnapshot你会得到订阅的句柄。当您将该句柄作为函数调用时,它会取消订阅进一步的更新。

所以在你的情况下:

this.sub();

推荐阅读