mobx icon indicating copy to clipboard operation
mobx copied to clipboard

Atomic design, mobx configurable inject

Open nadzic opened this issue 9 years ago • 3 comments

I have a:

question, how in mobx can I create components, which are observable and also reusable (It can depend on different store).

Currently we are passing down store as props and observing.. but for example if I have one component which can use two stores, and methods regarding that two stores, how can I inject dynamically different store with ("inject") or smth like that?

In one case I want... inject("store1").. component ... -> store1.callthisMethod() in second case I want... inject("store2").. component ... -> store2.callthisMethod()

But actually the component is the same component

nadzic avatar Aug 21 '17 06:08 nadzic

If you refer to mobx-react's inject, it also accepts a function which is itself reactive. So one idea is to have the condition expressed by something observable:

@inject((stores, props) => {  
  if (stores.someStore.somethingObservable) { // when "somethingObservable" changes the inject function re-runs
    return { store: stores.store1 } 
  } else {
    return { store: stores.store2 }
  }  
})

or if the condition is part of the recieved props

@inject((stores, props) => {  
  if (props.useStore1) {
    return { store: stores.store1 } 
  } else {
    return { store: stores.store2 }
  }  
}) 

urugator avatar Aug 21 '17 13:08 urugator

The generic solution without the @inject would most likely involve something like:

class Store {
  @computed get store() {
    if (this.somethingObservable) {
      return this.store1;
    } else {
      return this.store2;
    }
  }
}

// Then you would have some HOC which accepts this store and renders the component with the right store: 
return <Component store={this.props.store.store}>

// which is in principle the same as @inject, only the reactive function is placed elsewhere and props are used to pass deps instead of context 

urugator avatar Aug 21 '17 13:08 urugator

Closing as an answer has been provided

mweststrate avatar Aug 31 '17 11:08 mweststrate