getStore

Method to retrieve a store from outside a component.

After supplying your application with a store via the useProvider hook you can then call getStore outside of a component to access the store.

getStore(
  model: IAnyModelType,
  identifier?: any
): Instance<typeof model>

This method mirrors useStore with the only difference being that it can be called from outside of a React component. This is useful from within callbacks or other places where access to a store is needed outside of a component.

Available in version 2.1 or later

Parameters

  • model IAnyModelType

    The mobx-state-tree model you want to use/retrieve.

  • identifier (optional) any

    A unique identifier that tells mobx-store-provider which store you want to get access to.

Example

The following shows a basic example use of getStore:

// App.jsx
import React from "react";
import { useCreateStore, useProvider } from "mobx-store-provider";
import AppStore from "./AppStore";
import Header from './Header';

function App() {
  const Provider = useProvider(AppStore);
  const appStore = useCreateStore(AppStore);
  return (
    <Provider value={appStore}>
      <WhoAmI>
    </Provider>
  )
}

export default App;

In the above code, we use the AppStore model to both create and provide the store to the application.

// WhoAmI.jsx
import React from "react";
import { observer } from "mobx-react";
import { getStore } from "mobx-store-provider";
import AppStore from "./AppStore";

function getName() {
  // We use the store in this function
  const appStore = getStore(AppStore);
  alert(`I am ${appStore.user.name}!`);
}

function WhoAmI() {
  return <button onClick={getName}>Who am I?</button>;
}

export default observer(WhoAmI);

Calling the getStore method with the AppStore model retrieves the corresponding AppStore that was provided via the useProvider hook.

This is the AppStore model/store used with the example above:

// AppStore.js
import { types } from "mobx-state-tree";

const User = types.model({
  name: "Batman",
});

export default AppStore = types.model({
  user: types.optional(User, {}),
});

Next: Multiple stores