Ehssan Ehssan - 1 month ago 37
TypeScript Question

No chance to make an strongly typed object observable by mobx

I use mobx library. It fit well with ReactJS.
I have and observable array like this:

@observable items = [];


When I add an object in this way, I have no problem and the given object will be observable as expected.

let x = {
Title: "sample title"
}

items.push(x);


but when I define an strongly typed object (using typescript)

export class SampleObject {
Title: string;
constructor(title: string) {
this.Title = title;
}
}


and pushing new object in this way, It won't be observable

items.push(new SampleObject("Sample Title"));


How can I solve this problem !?

What's the differences between x and y ?!

var x = {
Title: "sample"
}

var y = new SampleObject("sample");

Answer

MobX only converts plain objects automatically to observable objects when assigning them to e.g. an array, because for class instances it might interfere with the internals of that class otherwise.

So in your class, just mark your fields (Title) as @observable as well and you should be good to go. See: https://mobxjs.github.io/mobx/refguide/object.html, second bullet