Reputation: 25743
I read the description of autorun and reaction multiple times, but it is still not clear to me which pattern to use when I detect a change in one observable and I want to update other observables.
Example
I have an address object shown below. Whenever the country changes, I want to reset/reinitialize all the other fields. One way to do this is to have an @action setCountry() {...}
inside the Address
class which takes care of setting the other observables. However, I don't have that luxury because my UI uses generic techniques to update store attributes, namely _.set(entity, attr, value)
. So I would like to use something like autorun
to detect the change and update the rest of the observables. What's the right way to do this?
class Address {
@observable name;
@observable line1;
@observable line2;
@observable city;
@observable state;
@observable zip;
@observable country;
...
}
Upvotes: 2
Views: 1051
Reputation: 112777
It sounds like observe would work well for your use case.
Example (JSBin)
class Address {
@observable name = '';
@observable line1 = '';
@observable line2 = '';
@observable city = '';
@observable state = '';
@observable zip = '';
@observable country = '';
}
const address = new Address();
observe(address, change => {
if (change.name === 'country' && change.newValue === 'Sweden') {
address.city = 'Stockholm';
}
});
autorun(() => {
console.log(toJS(address));
});
setTimeout(() => {
address.country = 'Sweden';
}, 2000);
Upvotes: 2