1
votes

I have a mobx observable object:

@observable friend = {name: 'bert'}

And I have a mobx action which updates the object:

@action addAge = () => this.friend.age = 20

But my friend object doesn't update.

I have looked into the mobx docs and it seems map may be the correct thing to use because it takes into account new items placed into an object. However this seems to be more tailored to arrays. extendObservable seems to be more tailored to classes.

What is good practise for adding to a mobx observable object?

1
If you know all the keys beforehand, you can use an object with null values, and it will work: observable friend = { name: 'bert', age: null };. If the keys can be totally dynamic, you need to use a map. - Tholle

1 Answers

2
votes

Map is the correct way to go about changing keys on on a object, as the map creates a keyed array.

Map works like the ES6 map in that it can take an iterable.

@observable friend = new Map([[ 'name', 'jack']])

At any point now friend can be modified using set.

@action addAge = () => { this.friend.set('age', 24); }

Anything using the friend observable will react to changes in values on existing keys and the addition or removal of new keys.