Mobx来自服务器的初始数据

问题描述 投票:0回答:2

如何从服务器端将mobx存储的值设置为初始值(来自fetch / http)?

import { computed, observable } from 'mobx';
import { Instrument } from '../models/core/instrument';

class ObservableInstrumentStore {
  //should set init value from server instead of setting to empty array
  @observable instruments: Instrument[] = [];

  @computed get getInstruments(): Instrument[] {
    return this.instruments;
  }

  addInstruments(instruments: Instrument[]): void {
    this.instruments = instruments;
  }
}

export const observableInstrumentStore = new ObservableInstrumentStore();
mobx mobx-react
2个回答
0
投票

如果不使用mobx和可观察物,您将如何做?

有一些选择。

  1. 等待数组的长度大于零,以便对数据进行处理。

  2. flag表示已完成数据加载,然后尝试对数据进行处理。


0
投票

我能够使用来自服务器的初始化数据来设置mobx存储,如下所示:

class ObservableInstrumentStore {
  @observable instruments: Instrument[] = [];

  @computed get getInstruments(): Instrument[] {
    return this.instruments;
  }

  addInstruments(instruments: Instrument[]): void {
    this.instruments = instruments;
  }

  async initializeInstruments(): Promise<void> {
    const response = await fetchInstruments();
    if (isRight(response)) {
      this.instruments = response.right;
    }
  }
}

const observableInstrumentStore = new ObservableInstrumentStore();
observableInstrumentStore.initializeInstruments().then();
export default observableInstrumentStore;
© www.soinside.com 2019 - 2024. All rights reserved.