Reputation: 3500
Please advise if it is correct to use mobx actions (https://mobx.js.org/refguide/action.html) to fetch remote api or do similar stuff:
@action readSomething() {
this.observableLoading = true;
executeRead(
this.param1,
mappedData => {
this.observableData = mappedData;
this.observableLoading = false;
},
() => {
console.log('error occurred');
},
);
}
If the approach does not violate idea behind mobx stores and store's action, how to report fetch errors? Introduce dedicated observable for errors pipeline?
Upvotes: 0
Views: 1131
Reputation: 301
I'll assume that executeRead
does something asynchronous before running it's second parameter action. In that case it is wrong usage. Action decorator will only apply to the first line in function. You can consult MobX docs here about this. What you can be doing instead is use runInAction
:
@action readSomething() {
this.observableLoading = true;
executeRead(
this.param1,
mappedData => {
runInAction(() => {
this.observableData = mappedData;
this.observableLoading = false;
})
},
() => {
console.log('error occurred');
},
);
}
Fetch errors definitely can be another observable if you want it to be seen on UI. Your observableLoading
could instead be observableState
and hold one of the "loading", "finished" or "error" states.
Upvotes: 1