Novice_Developer
Novice_Developer

Reputation: 39

How to communicate between Mobx stores created with React.createContext

I have my useStores.ts file which has two Mobx stores initialized in the following way.

import StoreA from "./stores/StoreA";
import StoreB from "./stores/StoreB";

const storesContext = createContext({
       storeA: new StoreA(),
       storeB: new StoreB(),
});

export const useStores = () => useContext(storesContext);

So I can use these stores inside any components in the following way.

const { storeA } = useStores();

But I'm not sure how to access storeA inside storeB.

Can someone please help me with the same?

Upvotes: 1

Views: 1102

Answers (1)

Ivan V.
Ivan V.

Reputation: 8081

You should create a root store that contains all other stores, and it passes itself to the child stores, so they can "go up" to the root store, and then to any other store.

class RootStore {
  storeA = new StoreA(this)
  storeB = new StoreB(this)
}


class StoreA{
  constructor(rootStore){
    this.rootStore = rootStore
    // get to store B 
    // this.rootStore.storeB
  }
}

Use with createContext

const storesContext = createContext(new RootStore());

Or even better, follow the dependency injection principles and pass child stores to root store in the RootStore constructor.

class RootStore {
  constructor(a,b){
    this.storeA = a
    this.storeB = b

    this.storeA.setRoot(this)
    this.storeB.setRoot(this)
}

const storesContext = createContext(new RootStore(new StoreA(),new StoreB());

Upvotes: 4

Related Questions