Tutorial on MobX toJS method

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

MobX has a function “toJS” that returns an Javascript structure from an observable object.  In this tutorial, we will use the “toJS” function to convert an MobX store to an Javascript object.  This can be useful if you were to dehydrate the store on the server to pass to the client to hydrate again (as in an isomorphic app).  In fact, we will use the ToDoStore.js from our earlier tutorial.

But first, we use create-react-app to start up a new React app and ran the eject script as described here.  Then create the ToDoStore.js in the “src” folder with the following contents (or copy the file from the previous tutorial)

Since the ToDoStore depends on axios, mobx, mobx-react, and babel-plugin-transform-decorators-legacy, we now install it with …

npm install axios mobx mobx-react babel-plugin-transform-decorators-legacy

For decorators to work, we also add the following to package.json…

Next, replace the index.js file in “src” with these contents …

In line 4, we fetch the ToDo items into the store.  The setTimeout is to give it five seconds before we convert the store to “jsObject” which console log out to browser console and then stringify to write out the JSON structure to the web page.

When you run “npm start” should should get this in your browser…

Note the “toJS” will output observable arrays, objects, maps and primitives. But will not output computed values and other non-enumerable properties.