Hook to access root store #1772
-
|
I was checking a way that I can access the root store from the components without the need to pass it down the props. I found this article here and it explains how to create a hook In the article it also states that I need to wrap my App with the provider. But I didnt get why this is necessary as it seems to be working fine without the need to use the StoreProvider with the rootStore as value: Also, I realized that with this approach the fix for the issue that is stated in this tutorial does not work. When I make any definition changes it throws an error saying the I can not use the Thanks in advance |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi @nigellima! The first argument given to Another approach is to just export the // stores/RootStore.ts
// ...
export const RootStore = types
.model({
dateFilterStore: DateFilterStore,
gaugesStore: GaugesStore,
continentsStore: ContinentsStore,
});
type IRootStore = Instance<typeof RootStore>;
export const rootStoresContext = createContext(null as IRootStore);
export const StoreProvider = rootStoresContext.Provider;
export const useStore = (): IRootStore => {
const store = useContext(rootStoresContext);
if (store === null) {
throw new Error('Store cannot be null, please add a context provider');
}
return store;
};
// index.ts
import React from 'react';
import ReactDOM from 'react-dom';
import { RootStore, StoreProvider } from './stores/RootStore';
import App from './components/App';
const rootStore = RootStore.create({
// ...
});
ReactDOM.render(
<StoreProvider value={rootStore}>
<App />
</StoreProvider>,
document.getElementById('root')
);I'm not sure how to fix the HMR issue. I tend to not use it when using MST myself. |
Beta Was this translation helpful? Give feedback.
Hi @nigellima!
The first argument given to
createContextwill be what is returned fromuseContextif there is noProviderabove the component in the tree. You could therefor opt for not using a provider at all and give aRootStoreinstance directly tocreateContext, as you have done in your code.Another approach is to just export the
RootStoreand create an instance of if outside of the module and give it to the provider. This can help a lot if you also need to create separate instances for e.g. testing.