0

I have a root Mobx store, with some children substores. Is there any way for me to pass just root store into React components, and from that component get access to children store's values as if this property was in root. What I mean exactly is, for example I have root store A and its child store B. Child store B has a property C. And from my react component I want to access C property easily by writing A.C . So, I want my root store to kinda accumulate all of it's children store's values. How can I achieve this? Or maybe that's a wrong way of working with mobx? Thank you

Leonid Gordun
  • 361
  • 1
  • 4
  • 14

2 Answers2

1

Don't do it. That is a major antipattern, why do you have multiple stores ( multiple objects) if, in the end, you are going to merge them into one? So by having multiple stores you have a separation of concerns. And each store carries its own data and methods to manipulate that data.

Root store is only used to put all the stores in one object, so it easy for components to get access to the stores they need.

Also, there is a possibility of collisions of the same property names and methods of multiple different stores, if they are all merged in one object.

Debugging will also be a lot harder.

Ivan V.
  • 7,593
  • 2
  • 36
  • 53
0

I am mostly agree with Ivan V. answer, but there might be cases when you want to "aggregate" something inside Root store or maybe some other store.

For example, you might want to do something like that:

class RootStore {
  constructor() {
    this.usersStore = new UsersStore(this);
    this.messagesStore = new MessagesStore(this);
  }

  @computed
  get totalInfo() {
    return `${this.usersStore.items.length} users and ${this.messagesStore.items.length} messages`
  }
}
Danila
  • 15,606
  • 2
  • 35
  • 67