KamSami
KamSami

Reputation: 407

How to get model/state to listen after a change is made in Mobx state tree?

I have two models/stores each referring to an object. Store2 gets populated after Store1 gets populated and receives a childId. How would I have Store2 listen to when Store1 gets populated?

Store1

import {action} from 'mobx'
import axios from "axios";
import {types} from "mobx-state-tree";

const Store1 = types.model('Store1', {
    id: types.number,
    name: types.string,
    description: types.string,
    childId: types.number
}).actions(self => ({
    onChange(name, value) {
        self[name] = value;
    },
    getInfo(id) {
        //API call that gets uses id and returns data
        self.id = data.id
        self.name = data.name
        self.description = data.description
        self.childId = data.childId
    },
}));

const store1 = Store1.create({
    id: 0,
    name: '',
    description: '',
    childId: 0
});
export default store1;

Store2 (Can't be populated until Store1 gets childId from API Call)

import {action} from 'mobx'
import axios from "axios";
import {types} from "mobx-state-tree";

const Store2 = types.model('Store2', {
    id2: types.number,
    name2: types.string,
    description2: types.string
}).actions(self => ({
    onChange(name, value) {
        self[name] = value;
    },
    //should receive id from store1 childId
    getInfo(childId) {
        //api call that gets info and returns data
        self.id2= data.id
        self.name2 = data.name
        self.description2 = data.description
    },
}));

const store2 = Store2.create({
    id2: 0,
    name2: '',
    description2: ''
});
export default store2;

Upvotes: 0

Views: 1199

Answers (1)

jayarjo
jayarjo

Reputation: 16726

If Store2 depends on Store1 for anything you better have a reference to it in the store2 instance. Then you can simply add a view observing a property of the store1 instance, that will auto-recompute itself, once the observed property updates.

Upvotes: 1

Related Questions