reactjsmobxmobx-react

Reactions inside the class


I'd like mobx to trigger a reaction whenever an observable changes. I want it to be trigerred inside the class that has that observable so the trigger method could manipulate other data in the store, for example data in a sub-store.

class Animal {
    name
    energyLevel

    constructor(name) {
        reaction(
            () => giraffe.isHungry,
            isHungry => {
                if (isHungry) {
                    console.log("Now I'm hungry!")
                } else {
                    console.log("I'm not hungry!")
                }
                console.log("Energy level:", giraffe.energyLevel)
            }
        )
        this.name = name
        this.energyLevel = 100
        makeAutoObservable(this)
    }

    reduceEnergy() {
        this.energyLevel -= 10
    }

    get isHungry() {
        return this.energyLevel < 50
    }
}

(The example is taken from the docs: https://mobx.js.org/reactions.html)

If I move the reaction inside the constructor function, it will not be triggered (in the original code it's outside the class). How can I trigger reactions inside the class?


Solution

  • First of all, to refer to the current instance of the class you need to use this keyword, like this.isHungry and etc.

    And second is that you need to use reaction after you use makeAutoObservable, so just move it in the end of constructor:

    class Animal {
      name;
      energyLevel;
    
      constructor(name) {
        this.name = name;
        this.energyLevel = 100;
        makeAutoObservable(this);
    
        reaction(
          () => this.isHungry,
          (isHungry) => {
            if (isHungry) {
              console.log("Now I'm hungry!");
            } else {
              console.log("I'm not hungry!");
            }
            console.log('Energy level:', this.energyLevel);
          }
        );
      }
    
      reduceEnergy() {
        this.energyLevel -= 60;
      }
    
      addEnergy() {
        this.energyLevel += 60;
      }
    
      get isHungry() {
        return this.energyLevel < 50;
      }
    }
    
    const animal = new Animal('cat');
    
    animal.reduceEnergy();
    animal.addEnergy();
    

    Edit https://stackoverflow.com/questions/74207374/mobx-reactions-inside-the-class