Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure mobx

I'm trying to figure out how to structure my app, for example, I have a model User, a generic UserStore to keep track all users load so far and some UI related stores like FriendList, PendingFriendList, BlockedUserList, LikedUserList, etc. like that:

class User {
  id;
  @observable name;
  @observable avatar;
  // others functions and fields
}

class UserStore {
  @observable users = [];
  function resolve(id) { /*return by id*/}
  function createOrUpdateUser(json) { /* add user to this.users */ }
}

class FriendStore {
  @observable users = [];
  hasNextPage = true;
  currentPage = null;

  function loadNextPage(page) {
    api.loadFriends(page >= 0 ? page : this.currentPage + 1).then( users => {
      users.forEach( user => {
        this.users.push( UserStore.createOrUpdateUser(user) )
      })
    })
  }
}

class PendingFriendUsers {
  @observable users = [];
  @observable query = null;
  hasNextPage = true;
  currentPage = null;

  function loadNextPage(page) {
    // more or less like FriendStore
  }
}

class BlockedUserStore {
  // more or less like FriendStore
}

My question is: Is that the way to go? Or is there a better way ??

like image 463
Maximiliano Guzenski Avatar asked Apr 29 '16 05:04

Maximiliano Guzenski


People also ask

Is MobX deprecated?

https://github.com/mobxjs/mobx/ is now monorepo with all the packages, so nothing is deprecated.

Is MobX better than Redux?

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.

Is MobX object oriented?

MobX: The object-oriented approach to state management - React.

Does MobX need state tree?

Ten reasons you should use MobX-State-Tree:Via runtime type checking, you can't accidentally assign the wrong data type to a property. TypeScript can infer static types from your runtime types automatically. Every update to your data is traced and you can quickly generate snapshots of your state at any time.


1 Answers

I've worked on some projects with Mobx & react, so I found this structure best suitable for me.

Stores

  • Domain Stores
    • stores the data which'll be needed in your app.
      for ex. user data
  • View Stores
    • stores the data which'll be needed to present your app
      for ex. loading, error variables

Models

  • Here you can define the data models
    for ex- user model

Services

  • Here you can make services, api calls

Components

  • Container or Smart Component
  • Dumb or presentational component
like image 153
Kuldeep Saxena Avatar answered Sep 21 '22 16:09

Kuldeep Saxena