Commit 5e4886cd authored by John Lombardo's avatar John Lombardo Committed by Tim Neutkens

Port with-mobx to with-mobx-react-lite (#6617)

Replicates the behaviour of the `with-mobx` example but implemented using `mobx-react-lite` and React context.

I'm still working out a best practice regarding actions and welcome feedback on anything.
parent 4c4459f9
{
"presets": [
"next/babel"
]
}
[![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-react-lite)
# MobX example
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example with-mobx-react-lite with-mobx-react-lite-app
# or
yarn create next-app --example with-mobx-react-lite with-mobx-react-lite-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-mobx-react-lite
cd with-mobx-react-lite
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## Notes
This example is a mobx-react-lite port of the [with-mobx](https://github.com/zeit/next.js/tree/master/examples/with-mobx) example. MobX support has been implemented using React Hooks:
## The idea behind the 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.
![](http://i.imgur.com/JCxtWSj.gif)
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 store and returning the initial timestamp to be rendered. The root component for the render method is a React context provider that allows us to send the store down to children components so they can access to the state when required.
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.
## Inplementation details
The initial store data is returned from the `initializeData` function that recycles existing store data if it already exists.
```jsx
function initializeData(initialData = store || {}) {
const { lastUpdate = Date.now(), light } = initialData
return {
lastUpdate,
light: Boolean(light),
}
}
```
The observable store is created in a function component by passing a plain JavaScript object to the `useObservable` hook. Actions on the observable store (`start` and `stop`) are created in the same scope as the `store` in `store.js` and exported as named exports.
```js
store = useObservable(initializeData(props.initialData))
start = useCallback(action(() => {
// Async operation that mutates the store
}))
stop = () => {
// Does not mutate the store
}
```
The component creates and exports a new React context provider that will make the store accessible to all of its descendents.
```jsx
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
```
The store is accessible at any depth by using the `StoreContext`.
```js
const store = useContext(StoreContext)
```
The clock, under `components/Clock.js`, reacts to changes in the observable `store` by means of the `useObserver` hook.
```jsx
return <div>
// ...
{useObserver(() => <Clock
lastUpdate={store.lastUpdate}
light={store.light}
/>)}
// ...
</div>
```
function Clock (props) {
return (
<div className={props.light ? 'light' : ''}>
{format(new Date(props.lastUpdate))}
<style jsx>{`
div {
padding: 15px;
color: #82fa58;
display: inline-block;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
}
const format = t =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = n => (n < 10 ? `0${n}` : n)
export default Clock
import { useObserver } from 'mobx-react-lite'
import Link from 'next/link'
import { useContext, useEffect } from 'react'
import { StoreContext, start, stop } from '../store'
import Clock from './Clock'
function Page ({ linkTo, title }) {
const store = useContext(StoreContext)
useEffect(() => {
start()
return stop
}, [])
return <div>
<h1>{title}</h1>
{useObserver(() => <Clock
lastUpdate={store.lastUpdate}
light={store.light}
/>)}
<nav>
<Link href={linkTo}>
<a>Navigate</a>
</Link>
</nav>
</div>
}
export default Page
{
"name": "with-mobx-react-lite",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"mobx": "^5.9.0",
"mobx-react-lite": "^1.1.1",
"next": "latest",
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"license": "ISC",
"devDependencies": {}
}
import App, { Container } from 'next/app'
import React from 'react'
import { InjectStoreContext, initializeData } from '../store'
class MyMobxApp extends App {
static async getInitialProps ({ Component, ctx }) {
let pageProps = {}
const initialStoreData = initializeData()
// Provide the store to getInitialProps of pages
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps({ ...ctx, initialStoreData })
}
return {
pageProps,
initialStoreData
}
}
render () {
const { Component, pageProps, initialStoreData } = this.props
return (
<Container>
<InjectStoreContext initialData={initialStoreData}>
<Component {...pageProps} />
</InjectStoreContext>
</Container>
)
}
}
export default MyMobxApp
import React from 'react'
import Page from '../components/Page'
export default class Counter extends React.Component {
render () {
return <Page title='Index Page' linkTo='/other' />
}
}
import React from 'react'
import Page from '../components/Page'
export default class Counter extends React.Component {
render () {
return <Page title='Other Page' linkTo='/' />
}
}
import { action } from 'mobx'
import { useObservable, useStaticRendering } from 'mobx-react-lite'
import { createContext, useCallback } from 'react'
const isServer = !process.browser
useStaticRendering(isServer)
let StoreContext = createContext()
let start
let stop
let store
function initializeData (initialData = store || {}) {
const { lastUpdate = Date.now(), light } = initialData
return {
lastUpdate,
light: Boolean(light)
}
}
function InjectStoreContext ({ children, initialData }) {
let timerInterval = null
store = useObservable(initializeData(initialData))
start = useCallback(action(() => {
timerInterval = setInterval(() => {
store.lastUpdate = Date.now()
store.light = true
}, 1000)
}))
stop = () => {
if (timerInterval) {
clearInterval(timerInterval)
}
}
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
export { InjectStoreContext, StoreContext, initializeData, start, stop, store }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment