Reputation: 152
I have a store myStore
which has a main
method which invokes multiple methods which are setting observale value in mobx. My problem is I want to re-render my react component only after ALL the observables are set.
can I make the main method @action
, even though it doesn't actually modify any observables directly? what is the standard practice for such scenarios ?
class myStore {
@observable var1;
@observable var2;
@action method1(val) {
this.var1 = val;
}
@action mathod2(val) {
this.var2 = val;
}
main() {
this.method1("some random value 1"); // Mobx may re-render the react component just after this line
this.method2("some random value 2");
// I want to re-render the component here(at the end of method)
}
}
Upvotes: 4
Views: 293
Reputation: 31
By using @action on the main method, you ensure that even though the method itself doesn't modify any observables directly, MobX treats the entire process as a single atomic operation for reactivity purposes. This means that the component will only re-render after all the observable changes are complete.
import { observable, action } from 'mobx';
class myStore {
@observable var1;
@observable var2;
@action method1(val) {
this.var1 = val;
}
@action method2(val) {
this.var2 = val;
}
@action main() {
this.method1("some random value 1");
this.method2("some random value 2");
// No direct observables are modified here, but using @action will ensure reactivity
}
}
Upvotes: 1