How to add stores to mobx-react Provider when they are dependent to each other?

1.2k views Asked by At

What is the best practice of initializing a store based on another one and put both of them in Provider? I have a store called AuthManager it owns an observeable property called user. Also I have another store called GoalManager. I need the user property of AuthManager to initialize GoalManager. I want to construct GoalManager like this:

const goalManager = new GoalManager(user);

But it is not possible to add something later in react's context because some children cannot update based on changes of context! I solved this problem by sending AuthManager instance to GoalManager's constructor, but I don't like it:

// services.js

const authManager = new AuthManager();
const goalManager = new GoalManager(authManager);

export default {
  authManager,
  goalManager
}

and later:

// index.jsx

import services from './services';

render(`
  <Provider {...services}>
    <App />
  </Provider>`, mountPoint);

I don't like this solution because I had to depend GoalManager to AuthManager but it only depends on AuthManager.user. Then testing GoalManager is harder (because you have to mock a big object).

Is there any better solution for that?

1

There are 1 answers

3
webdeb On BEST ANSWER

Maybe a completely other way of thinking, but this would solve your problem.

It looks like, this would work for you too:

// AuthManager.js
class AuthManager {
  @observable user;
}

export default new AuthManager();

And just import AuthManager in GoalManager to use AuthManger.user

// GoalManager.js

// import the AuthManager and use the user directly.
import AuthManager from './AuthManager'

class GoalManager {
  @computed get someThing() {
     if (AuthManager.user) {
       // your stuff..
     }
  }
}

export default new GoalManager();

in services you'll get the instances so.

// services.js

import authManager from './AuthManager'
import goalManager from './GoalManager'

export default {
  authManager,
  goalManager
}

Do you got the idea?