Michal
Michal

Reputation: 5226

MobX Store Responsibilities

I recently started working on a project with MobX. I never used MobX before so I am quite confused about one thing.

What are MobX store responsibilities?

1) Should MobX @action, @computed return html/jsx? In official 10 minutes MobX tutorial https://mobx.js.org/getting-started.html there is a @computed get report. That is just an example right?

@computed get report() {
    if (this.todos.length === 0)
        return "<none>";
    return `Next todo: "${this.todos[0].task}". ` +
        `Progress: ${this.completedTodosCount}/${this.todos.length}`;
}

2) Is it a good idea to call API in @action? Like this?

@action
submitProfileInformation = params => {
  return post("apiendpoint", {
    body: params
  }).then(resp => {
    this.firstName = resp.first_name;
    return "ok";
  });
};

I come from the redux world and the way I see it store should only store and mutate values. Actions would react component let know that something has changed so that they would rerender. Is that correct?

Upvotes: 3

Views: 663

Answers (2)

XPX-Gloom
XPX-Gloom

Reputation: 601

MobX store is for storing application states, including observable and non-observable data. (similar to Redux Stores, although Redux doesn't have observable)

MobX actions are any functions that modify the observable data. There's no rule saying that you must put actions in store, but it's good practice to do so.

For you question: Actions would react component let know that something has changed so that they would rerender. Answer is yes and no. Actions are functions that modify observable data. Your observer components react to changes of observable data, not action functions. But since actions always modify observable data, so calling an action function should trigger observer components to react.

@computed decorator simply creates observable data that is computed from other observable data (similar to getter functions)

Upvotes: 0

Ehsan
Ehsan

Reputation: 1113

  1. It doesn't return any html or jsx. It's just a sample and it returns only string.
  2. Only the then section should be marked as action.

Concepts are the same. It's up to you to follow the best practices or abusing flexiblity of mobx and doing bad things. I recommand you to read this article: https://mobx.js.org/best/store.html

Upvotes: 2

Related Questions