How can I access mobx store in another mobx store?

Viewed 9229

Assume following structure

stores/
  RouterStore.js
  UserStore.js
  index.js

each of ...Store.js files is a mobx store class containing @observable and @action. index.js just exports all stores, so

import router from "./RouterStore";
import user from "./UserStore";

export default {
  user,
  router
};

What is correct way to access one store inside another? i.e. inside my UserStore, I need to dispatch action from RouterStore when users authentication changes.

I tired import store from "./index" inside UserStore and then using store.router.transitionTo("/dashboard") (transitionTo) is an action within RouterStore class.

But this doesn't seem to work correctly.

2 Answers

In this case you just need to pass only one link

Just create global store and pass link of the GlobalStore to every children stores where you need to get access:

// global parent store
class GlobalStore {
    constructor() {
        this.routerStore = new RouterStore(this);
        this.userStore = new UserStore(this);
        // ... another stores
    }
}

// access in child
class UserStore {
    constructor(rootStore) {
        this.routerStore = rootStore.routerStore;
    }

    // ...
}

// In root component:
<MobxProvider {...new GlobalStore()}>
  <App />
</MobxProvider>
Related