0

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?

ror
  • 3,295
  • 1
  • 19
  • 27

1 Answers1

1

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.

Rena
  • 301
  • 1
  • 6
  • Thank you for your answer cannot verify at the moment in order to accept, but up voting. – ror Feb 19 '20 at 21:11