Skip to content

Commit a8c344f

Browse files
dargue3timneutkens
authored andcommitted
Add with-mobx-state-tree example (vercel#3179)
* Adapt with-mobx example for with-mobx-state-tree * Remove unnecessary lastUpdate parameter to show off snapshot * update readme * make other.js more closely mimic index.js
1 parent bda073c commit a8c344f

File tree

9 files changed

+258
-0
lines changed

9 files changed

+258
-0
lines changed
+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"presets": [
3+
"next/babel"
4+
],
5+
"plugins": [
6+
"transform-decorators-legacy"
7+
]
8+
}
+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree)
2+
3+
# MobX State Tree example
4+
5+
## How to use
6+
7+
Download the example [or clone the repo](https://github.com/zeit/next.js):
8+
9+
```bash
10+
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-mobx
11+
cd with-mobx
12+
```
13+
14+
Install it and run:
15+
16+
```bash
17+
npm install
18+
npm run dev
19+
```
20+
21+
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
22+
23+
```bash
24+
now
25+
```
26+
## Notes
27+
This example is a mobx port of the [with-redux](https://github.com/zeit/next.js/tree/master/examples/with-redux) example. Decorator support is activated by adding a `.babelrc` file at the root of the project:
28+
29+
```json
30+
{
31+
"presets": [
32+
"next/babel"
33+
],
34+
"plugins": [
35+
"transform-decorators-legacy"
36+
]
37+
}
38+
```
39+
40+
### Rehydrating with server data
41+
After initializing the store (and possibly making changes such as fetching data), `getInitialProps` must stringify the store in order to pass it as props to the client. `mobx-state-tree` comes out of the box with a handy method for doing this called `getSnapshot`. The snapshot is sent to the client as `props.initialState` where the pages's `constructor()` may use it to rehydrate the client store.
42+
43+
## The idea behind the example
44+
45+
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.
46+
47+
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.
48+
49+
![](http://i.imgur.com/JCxtWSj.gif)
50+
51+
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the mobx-state-tree store and returning the initial timestamp to be rendered. The root component for the render method is the `mobx-react <Provider>` that allows us to send the store down to children components so they can access to the state when required.
52+
53+
To pass the initial timestamp from the server to the client we pass it as a prop called `lastUpdate` so then it's available when the client takes over.
54+
55+
The trick here for supporting universal mobx is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`
56+
57+
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.
58+
59+
As far as how this example differs from the `with-mobx` example, `mobx-state-tree` requires that any changes to the observable data are sent as actions, which are defined on the model in `server.js`. The snapshot feature, while not very useful in this particular case, makes client-side rehydration of the state amazingly easy. Any changes that are made to the store in `getInitialProps` will be refreshed instantly when that page is loaded on the client.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export default (props) => {
2+
return (
3+
<div className={props.light ? 'light' : ''}>
4+
{format(new Date(props.lastUpdate))}
5+
<style jsx>{`
6+
div {
7+
padding: 15px;
8+
color: #82FA58;
9+
display: inline-block;
10+
font: 50px menlo, monaco, monospace;
11+
background-color: #000;
12+
}
13+
14+
.light {
15+
background-color: #999;
16+
}
17+
`}</style>
18+
</div>
19+
)
20+
}
21+
22+
const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
23+
24+
const pad = n => n < 10 ? `0${n}` : n
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import React from 'react'
2+
import Link from 'next/link'
3+
import { inject, observer } from 'mobx-react'
4+
import Clock from './Clock'
5+
6+
@inject('store') @observer
7+
class Page extends React.Component {
8+
componentDidMount() {
9+
this.props.store.start()
10+
}
11+
12+
componentWillUnmount() {
13+
this.props.store.stop()
14+
}
15+
16+
render() {
17+
return (
18+
<div>
19+
<h1>{this.props.title}</h1>
20+
<Clock lastUpdate={this.props.store.lastUpdate} light={this.props.store.light} />
21+
<nav>
22+
<Link href={this.props.linkTo}><a>Navigate</a></Link>
23+
</nav>
24+
</div>
25+
)
26+
}
27+
}
28+
29+
export default Page
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "with-mobx",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"dev": "node server.js",
6+
"build": "next build",
7+
"start": "NODE_ENV=production node server.js"
8+
},
9+
"dependencies": {
10+
"mobx": "3.3.1",
11+
"mobx-react": "^4.0.4",
12+
"mobx-state-tree": "1.0.1",
13+
"next": "latest",
14+
"react": "^16.0.0",
15+
"react-dom": "^16.0.0"
16+
},
17+
"license": "ISC",
18+
"devDependencies": {
19+
"babel-plugin-transform-decorators-legacy": "^1.3.4"
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import React from 'react'
2+
import { Provider } from 'mobx-react'
3+
import { getSnapshot } from 'mobx-state-tree'
4+
import { initStore } from '../store'
5+
import Page from '../components/Page'
6+
7+
export default class Counter extends React.Component {
8+
static getInitialProps({ req }) {
9+
const isServer = !!req
10+
const store = initStore(isServer)
11+
return { initialState: getSnapshot(store), isServer }
12+
}
13+
14+
constructor(props) {
15+
super(props)
16+
this.store = initStore(props.isServer, props.initialState)
17+
}
18+
19+
render() {
20+
return (
21+
<Provider store={this.store}>
22+
<Page title='Index Page' linkTo='/other' />
23+
</Provider>
24+
)
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import React from 'react'
2+
import { Provider } from 'mobx-react'
3+
import { getSnapshot } from 'mobx-state-tree'
4+
import { initStore } from '../store'
5+
import Page from '../components/Page'
6+
7+
export default class Counter extends React.Component {
8+
static getInitialProps({ req }) {
9+
const isServer = !!req
10+
const store = initStore(isServer)
11+
return { initialState: getSnapshot(store), isServer }
12+
}
13+
14+
constructor(props) {
15+
super(props)
16+
this.store = initStore(props.isServer, props.initialState)
17+
}
18+
19+
render() {
20+
return (
21+
<Provider store={this.store}>
22+
<Page title='Other Page' linkTo='/' />
23+
</Provider>
24+
)
25+
}
26+
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const port = parseInt(process.env.PORT, 10) || 3000
2+
const dev = process.env.NODE_ENV !== 'production'
3+
4+
const { createServer } = require('http')
5+
const { parse } = require('url')
6+
const next = require('next')
7+
const mobxReact = require('mobx-react')
8+
const app = next({ dev })
9+
const handle = app.getRequestHandler()
10+
11+
mobxReact.useStaticRendering(true)
12+
13+
app.prepare().then(() => {
14+
createServer((req, res) => {
15+
const parsedUrl = parse(req.url, true)
16+
handle(req, res, parsedUrl)
17+
}).listen(port, err => {
18+
if (err) throw err
19+
console.log(`> Ready on http://localhost:${port}`)
20+
})
21+
})
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { types, applySnapshot } from 'mobx-state-tree'
2+
3+
let store = null
4+
5+
const Store = types
6+
.model({
7+
lastUpdate: types.Date,
8+
light: false,
9+
})
10+
.actions((self) => {
11+
let timer;
12+
function start() {
13+
timer = setInterval(() => {
14+
// mobx-state-tree doesn't allow anonymous callbacks changing data
15+
// pass off to another action instead
16+
self.update();
17+
})
18+
}
19+
20+
function update() {
21+
self.lastUpdate = Date.now()
22+
self.light = true
23+
}
24+
25+
function stop() {
26+
clearInterval(timer);
27+
}
28+
29+
return { start, stop, update }
30+
})
31+
32+
33+
export function initStore(isServer, snapshot = null) {
34+
if (isServer) {
35+
store = Store.create({ lastUpdate: Date.now() })
36+
}
37+
if (store === null) {
38+
store = Store.create({ lastUpdate: Date.now() })
39+
}
40+
if (snapshot) {
41+
applySnapshot(store, snapshot)
42+
}
43+
return store
44+
}

0 commit comments

Comments
 (0)