Tina Raissi
Tina Raissi

Reputation: 41

How can I inject a Store to another Store in mobX

I am using mobX in combination with React and Meteor and I need to be able to use information saved in one Store in another. Specifically, I need to have a reference of Store A in Store B in order to call an action of Store A and get the information that it had retrieved by subscribing to a collection. I used the @inject decorator but do not know how to call the action. Thank you

Upvotes: 4

Views: 8289

Answers (2)

H.ilkhani
H.ilkhani

Reputation: 16

you can do it via following steps

// store1.js
import { observable, action } from 'mobx';

class Store1 {
  @observable count = 0;

  @action increment() {
    ++this.count;
  }
}

export default new Store1();

// store2.js
import { observable, action } from 'mobx';
import store1 from './store1';
const store = new store1()

class Store2 {
  @observable name = 'foobar';

  @action changeName(name) {
    this.name = name;
  }

@action
increment(){
 store.increment();
}
}

export default new Store2();

Upvotes: 0

Tholle
Tholle

Reputation: 112777

@inject is used to inject something from the Provider into a React component, not between stores.

You could just import the first store into the second store and call the action straight away.

Example

// store1.js
import { observable, action } from 'mobx';

class Store1 {
  @observable count = 0;

  @action increment() {
    ++this.count;
  }
}

export default new Store1();

// store2.js
import { observable, action } from 'mobx';
import store1 from './store1';

class Store2 {
  @observable name = 'foobar';

  constructor() {
    store1.increment();
  }

  @action changeName(name) {
    this.name = name;
  }
}

export default new Store2();

Upvotes: 7

Related Questions