【问题标题】:Correct synchronization firestore collection in MobX在 MobX 中正确同步 Firestore 集合
【发布时间】:2019-08-28 15:20:01
【问题描述】:

我正在尝试从 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-firestore synchronization mobx


【解决方案1】:

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

所以在你的情况下:

this.sub();

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2020-09-24
    • 1970-01-01
    • 2021-07-24
    • 2020-06-05
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多