0

Сan I use the Mobx library to call a class method when data changes?

For example MyObject writes container['item'] = 10 and as a result the myaction method is called.

class MyElement extends Component<any> {

    // modifiable data
    container: any = [];

    // method called when data (container) is modified
    myaction() {
        console.log('container was modified');
        console.log(this.container);
    }

    render() {
        <MyObject container = {this.container} />
    }
}

decorate(MyElement, {
    container: observable
} as any)
Zhihar
  • 1,306
  • 1
  • 22
  • 45

1 Answers1

1

You could use reaction for example:

  container = [];

  componentDidMount() {
    // save disposer function to use later inside componentWillUnmount
    this.reactionDisposer = reaction(
      () => this.container.length,
      () => {
        console.log('container was modified')
      }
    );
  }

  // Don't forget to dispose it when unmount
  componentWillUnmount() {
    this.reactionDisposer();
  }

Codesandbox link: https://codesandbox.io/s/httpsstackoverflowcomquestions63864175-kjorh?file=/src/App.js

Also, technically you can do that with array container['item'] = 10, but I advise you not to use string keys with array. If you want to use string keys then you need to use object or a Map.

Other methods you could also use to achieve what you want:

Danila
  • 15,606
  • 2
  • 35
  • 67