Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create a single MobX store for an app?

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.

like image 439
Tanner Plauché Avatar asked Mar 30 '17 19:03

Tanner Plauché


People also ask

Is MobX better than Redux?

2. Debug process: Compared to MobX, debugging in Redux is a better experience because it has more developer tools and less abstraction. The Redux becomes more predictable with the flux paradigm. Debugging in MobX is much more difficult due to increased abstraction and average developer tools.

How do you persist MobX?

To simply persist your MobX store use makePersistable . Pass a reference of the store ( this ) as the first argument. The second argument is the StorageOptions for persisting the store data.

Is MobX fast?

MobX is very fast, often even faster than Redux, but here are some tips to get most out of React and MobX. Most apply to React in general and are not specific to MobX. Note that while it's good to be aware of these patterns, usually your application will be fast enough even if you don't worry about them at all.


1 Answers

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.

like image 165
Petr Avatar answered Sep 28 '22 16:09

Petr