Search code examples
javascriptmobxmobx-state-tree

How to call an mobx-state-tree action if a computed view changes?


Basically what I'm trying to do is to call an action if a computed view changes.

const Store = types
  .views(self => ({
    get computedValue() {
      return somethingComputed;
    }
  }))
  .actions(self => ({
    doSomething() {
      doSomeStuffUsingComputedValue(self.computedValue);
    }
  }));

I want to call doSomething action if computedValue changes. I don't have control of the what updates computedValue.

Any idea of how can I achieve this?


Solution

  • You can use mobx autorun, when or reaction to do it.

    For example, this reaction will trigger each time computedValue changes:

    import { reaction } from 'mobx'
    
    reaction(
      () => store.computedValue,
      () => store.doSomething()
    )
    

    You can read more about these mobx utilities in the mobx documentation: https://mobx.js.org