Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 960 of the free egghead.io lessons, plus get React content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Connect MobX observer components to the store with the React Provider

1:33 React lesson by

Passing down stores through each layer of components can be a tedious job. This lesson demonstrates how Provider can be used to automatically connect observer based components to stores, by leveraging React's context mechanism in the background.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Passing down stores through each layer of components can be a tedious job. This lesson demonstrates how Provider can be used to automatically connect observer based components to stores, by leveraging React's context mechanism in the background.

Avatar
nader dabit

I'm having a hard time getting the final code to run. I'm getting MobX observer: Store 'temperatures' is not available! Make sure it is provided by some Provider as an error message. I've also tried running the example jsbin with my own api key and it doesn't seem to work. Any ideas? Thanks.

In reply to egghead.io

As you might have noticed so far, it really doesn't matter where observable state is defined. It can be either in a model class, or it can be in our components, or in our store. For MobX, for observed components, it doesn't matter where the observables are coming from. If they are used, it will react to them.

If you have a deeply-nested component tree, it quickly might become annoying to pass this temperature collection along each time. Luckily, React has a mechanism for that. It's called context. MobX leverages this concept to be able to pass around stores.

If you consider our temperatures collection as a store, you could just initialize that store once, like in the root of our application. From there, we can use the provider components to pass it to any components in the component tree that is interested in the store.

We declare that we provide temperatures. Then, in any component deeper in the tree, we can just declare that it wants temperatures. The only thing we need to do for that is providing an array of store names we are interested in.

MobX will make sure that these store are passed into the component as a property. That is ideal for testing as well, because during testing, you can just directly pass in the stores as props to the components, while in your real component tree, those are passed down via the provider.

In our app components, we no longer have to explicitly pass down temperatures to the temperature input. We see that everything is still working as before.



HEY, QUICK QUESTION!
Joel's Head
Why are we asking?