Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a plain object from mobx object?

I defined a mobx map as below:

@observable editors = observable.map();

then I added object on the editors as below:

  editors.set(key, {
    alias: 'alias-1',
    message: 'hello',
  })

when I get the object from editor as below:

  let myEditor = editors.get(key)

the returned object myEditor has some builtin functions such as:

$mobx:ObservableObjectAdministration
get alias:function ()
set alias:function ()
get message:function ()
set message:function ()

I wander how I can get a plain javascript object from editor?

like image 260
Joey Yi Zhao Avatar asked Apr 12 '17 05:04

Joey Yi Zhao


People also ask

What does @observable do in MobX?

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.

What is toJS in MobX?

Usage: toJS(value) Recursively converts an observable object to a JavaScript object. Supports observable arrays, objects, Maps and primitives.

What is observable ref?

observable. ref will only track reference changes to the object, which means that you will need to change the whole object in order to trigger the reaction. So if you, for example, have an observable array that is tracked by reference, the contents of the array will not be tracked.


1 Answers

You can use toJS.

Example

class MyStore {
  @observable editors = observable.map({});
}

const myStore = new MyStore();

myStore.editors.set('example', {
  alias: 'alias-1',
  message: 'hello'
});

console.log(toJS(myStore.editors));
like image 92
Tholle Avatar answered Oct 07 '22 12:10

Tholle