0

I'm currently using Mobx-State-Tree to manage all of the state for a form in my React application. The issue I'm facing is that I want to create the store at the page level, following atomic design, of the form and pass the store down to the necessary components via React Context, but I want to avoid wrapping my child component in <Observer> tags from Mobx-react, or having some kind of custom wrapper on my child that consumes the store and passes it in as a prop to the child.

There must be a best practice around this? The Mobx-react documentation states:

"It is possible to read the stores provided by Provider using React.useContext, by using the MobXProviderContext context that can be imported from mobx-react."

But then I'm unable to find any examples or explanation of how best to implement MobXProviderContext ? My current setup is as follows (hugely simplified to demonstrate the situation):

import { types } from "mobx-state-tree";

const ExampleContext = React.createContext("default");

const exampleStore = types.model({ prop: types.optional(types.string, "") }).create();

const ChildComponent = () => (
  <ExampleContext.Consumer>
    {example => <Observer>{() => <div>{example.prop}</div>}</Observer>}
  </ExampleContext.Consumer>
);

const ParentComponent = () => (
<ExampleContext.Provider value={exampleStore}>
   <ChildComponent />
</ExampleContext.Provider>
);

Ultimately I'm interested in how to avoid the nesting on the child component? How should I be constructing the child component? The situation I'm applying this to is the state management of a form so the store data is constantly being updated, so it is crucial that the child is observing any updates to the values in the store.

Hope that makes sense and really appreciate any guidance on how best to approach this!

Joe Devine
  • 138
  • 1
  • 12
  • See if this brings you closer to the solution: https://stackoverflow.com/questions/54393475/correct-way-of-creating-multiple-stores-with-mobx-and-injecting-it-into-to-a-com – jayarjo Jun 29 '19 at 07:49
  • Also not sure why you want to avoid using Observer wrapper. It simply subscribes the component to the observables and computables. Isn't that what you want? – jayarjo Jun 29 '19 at 07:50

1 Answers1

0

Please use inject to inject store to your component. You can build your own provider as well in order to pass store to all child.

Kiran
  • 1
  • 3