MobX + React. Reactions. Is it possible to listen to actions?

Viewed 88

For example

There is a store:

const DataStore = observable({
   data: [],
   getDataAction() {}
})

And there are also other stores.

All of them are used in:

injectStores({ store, storeY })

in order to MobX DevToolsPro work.

Official documentation says, that you can use methods:

autorun()
reaction()
when()

All examples are given with classes. And if I understood it right, you can listen only to state changes.

For example, if

data != []

you can call

console.log("data is not empty")

or anything you want.

Question Section:

It is possible to listen not to

data != []

, but to

getDataAction()

and, if getDataAction was called, then

console.log("getDataAction was called")

?

If it is not possible, can I create then store not with classes, but also with observable( { } ) for using together with autorun(), reaction() and when()? Or all this methods only work with stores, which were created with classes syntax?

Thank You

1 Answers

You can use spy for that, for example:

import { action, makeAutoObservable, spy } from 'mobx';

const DataStore = makeAutoObservable(
  {
    data: [],
    getDataAction() {
      console.log('inside of getDataAction');
    }
  },
  {
    getDataAction: action('getDataAction')
  }
);

spy((event) => {
  if (event.type === 'action' && event.name === 'getDataAction') {
    console.log('getDataAction spy callback');
  }
});

DataStore.getDataAction();

I don't know what you are trying to do with it, but if are just starting with MobX and you want to use this approach in your app code then it's probably a bad practice and not a right thing to do and you should rethink your approach.

Related