Is there any way that a console.log
will automatically fire whenever a mobx @observable
changes value?
I would do it with mobx dev tools but it fires a huge amount of console logs so it's hard to pin point the property whose value I am tracking.
observable defines a trackable field that stores the state. action marks a method as action that will modify the state. computed marks a getter that will derive new facts from the state and cache its output.
Observables in MobX allow us to add observable capabilities to our data structures—like classes, objects, arrays—and make our properties observables. That means that our property stores a single value, and whenever the value of that property changes, MobX will keep track of the value of the property for us.
Autorun works by running the effect in a reactive context. During the execution of the provided function, MobX keeps track of all observable and computed values that are directly or indirectly read by the effect.
Using trace for debugging It can be used by simply importing import { trace } from "mobx" , and then putting it inside a reaction or computed value. It will print why it is re-evaluating the current derivation. Optionally it is possible to automatically enter the debugger by passing true as the last argument.
You can do:
//store.js
import { autorun } from 'mobx';
autorun(() => {
console.log(store.value); //value is an observable.
});
You can also use Reaction, For logging you'll probably want to use autorun, but you should know there's another option, which can gives you more control over when to run your callback.
I also like it because the syntax makes more sense:
import { reaction } from 'mobx'
class SomeStore {
@observable item;
@observable otherObservable;
constructor() {
reaction(
// The callback will run only on change
// of observables described in this function
() => this.item,
// You can use whatever observables/computed values in this function
// without making the function run on an unwanted observables change
() => {
if (this.otherObservable) {
doSometing();
}
}
)
}
}
There are more options to this function, you can read about it in the provided link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With