rsnext/examples/with-mobx/README.md
Luis Alvarez D 1239d5af59
[Examples] Update mobx examples to not use SSR (#11576)
* Updated with-custom-reverse-proxy

* Updated readme of with-env-from-next-config-js

* Updated the kea example

* Updated with-mobx

* Updated with-mobx readme

* Updated the with-mobx-react-lite example
2020-04-07 09:48:13 -04:00

2.9 KiB

MobX example

Usually splitting your app state into pages feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use mobx that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.

In this example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.

The clock, under components/Clock.js, has access to the state using the inject and observer functions from mobx-react. In this case Clock is a direct child from the page but it could be deep down the render tree.

This example is a mobx port of the with-redux example. Decorator support is activated by adding a .babelrc file at the root of the project:

{
  "presets": ["next/babel"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

Deploy your own

Deploy the example using ZEIT Now:

Deploy with ZEIT Now

How to use

Using create-next-app

Execute create-next-app with npm or Yarn to bootstrap the example:

npm init next-app --example with-mobx with-mobx-app
# or
yarn create next-app --example with-mobx with-mobx-app

Download manually

Download the example:

curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-mobx
cd with-mobx

Install it and run:

npm install
npm run dev
# or
yarn
yarn dev

Deploy it to the cloud with ZEIT Now (Documentation).

Rehydrating with server data

Be aware that data that was used on the server (and provided via one of Next.js data fetching methods) will be stringified in order to rehydrate the client with it. That means, if you create a store that is, say, an ObservableMap and give it as prop to a page, then the server will render appropriately. But stringifying it for the client will turn the ObservableMap to an ordinary JavaScript object (which does not have Map-style methods and is not an observable). So it is better to create the store as a normal object and turn it into a Observable in the render() method. This way both sides have an Observable to work with.