Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 414
Charanjit Singh Avatar asked Oct 24 '25 14:10

Charanjit Singh


1 Answers

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

like image 96
Tony Caputo Avatar answered Oct 27 '25 07:10

Tony Caputo