14

I have been using MobX and Redux for about 6 months. I have found that I prefer the simplicity of MobX for most applications. However, I like the single store concept of Redux. I have heard others comment that they create a single story with MobX and I am trying trying to determine the best way. Currently I create a multiple stores and then import them into a single store.

class UiStore {
  @observable uiData;

  constructor() {
    this.uiData = {}
  }

  @action updateUI = (data) => {
    this.uiData = {
      data: data
    };
  }
}

let uiStore = new UiStore();
export default uiStore;
class Store {
  @observable currentUser;

  constructor() {
    this.auth = authStore;
    this.ui = uiStore;
  }

}

let store = new store();
export default store;

Here I basically create individual stores that are then combined into a single store similar to how a redux reducer works.

Is there another / better way? I've thought about maybe import the a store in to different files and putting some methods and data on a class's prototype.

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Tanner Plauché
  • 165
  • 1
  • 10

1 Answers1

21

I use MobX for a year+ now and I basically do the same:

1) I have one "master" or "parent" store usually named as class Store {...}

2) Then I have some smaller stores that are kept in "master" store.

3) I prefer to construct children stores within master's store constructor. Moreover, I found that sometimes my child store has to observe some data from parent store, so I pass this into child constructors:

class UserStore {...}
class TodosStore {...}

class Store {
  constructor() {
    this.user = new UserStore(this);
    this.todos = new TodosStore(this);
  }
}

Parent keeps references to children, and each child has reference to parent.

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Petr
  • 6,697
  • 1
  • 14
  • 16
  • Great. Thanks for the feedback! – Tanner Plauché Apr 17 '17 at 04:15
  • How to inject particular store to a component? Can you please elaborate on your answer? – uneet7 Jan 27 '19 at 17:38
  • I have posted my question [here](https://stackoverflow.com/questions/54393475/correct-way-of-creating-multiple-stores-with-mobx-and-injecting-it-into-to-a-com). Can you please have a look and answer the isuue? – uneet7 Jan 28 '19 at 07:06