Leandro Oriente
Leandro Oriente

Reputation: 103

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?

Upvotes: 0

Views: 1688

Answers (1)

Luis Herranz
Luis Herranz

Reputation: 386

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

Upvotes: 1

Related Questions