Search code examples
reactjsmobxmobx-reactmobx-state-tree

How to make class objects observable in MobX?


I've a class as:

class Field{

  constructor(name) {
    this.name= name
    this.otherAttr = null
  }

  changeName(newName) {
    this.name = newName
  }
}


const f = new Field("Charanjit")
f.setName("Singh") // It shoukd reflect in observer 

f.name = "Rahul" // It should also reflect in observer


How to make f object observable such that any changes in f's attributes, update the observer components.

Currently, I'm getting error: https://github.com/mobxjs/mobx/issues/1932 if I use:

@observable(f)
>>> It shows Error: https://github.com/mobxjs/mobx/issues/1932

Solution

  • Looking at MobX documentation, It would be probably a good approach doing something like that:

    import { observable, action, decorate } from "mobx";
    
    class Field {
        name = '';
        otherAttr = null;
    
        changeName(name) {
            this.name = name;
        }
    }
    
    decorate(Field, {
        name: observable,
        otherAttr: observable,
        changeName: action
    })
    

    Mark properties as observables with the decorate utility will do what are you looking for. Please go through the docs: https://mobx.js.org/best/decorators.html