4

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)
    }
}
      
Prashant
  • 122
  • 7
  • Yes, just make it an action too, it should solve the problem. – Danila Aug 18 '23 at 12:39
  • In this scenario, when you call main, the React component observing var1 and var2 will only re-render once, after both values have been updated. – Xab Ion Aug 31 '23 at 13:21

1 Answers1

1

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
    }
}