Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`console.log` a mobx `@observable` whenever its value changes

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.

like image 942
alanbuchanan Avatar asked Feb 02 '17 13:02

alanbuchanan


People also ask

What is MobX observable?

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.

How does MobX observable work?

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.

How does MobX Autorun work?

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.

How do you debug a MobX React?

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.


2 Answers

You can do:

//store.js
import { autorun } from 'mobx';
autorun(() => {
  console.log(store.value); //value is an observable.
});
like image 130
Hosar Avatar answered Oct 28 '22 22:10

Hosar


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.

like image 23
AmitBu Avatar answered Oct 28 '22 22:10

AmitBu