如何从服务器端将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和可观察物,您将如何做?
有一些选择。
等待数组的长度大于零,以便对数据进行处理。
flag
表示已完成数据加载,然后尝试对数据进行处理。
我能够使用来自服务器的初始化数据来设置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;