未验证 提交 282f3751 编写于 作者: L Luis Alvarez D 提交者: GitHub

[Examples] Update with-mobx-state-tree examples (#11736)

* Updated with-mobx-state-tree

* Updated with-mobx-state-tree-typescript

* minor fix
上级 17384fc0
# MobX State Tree example
# MobX State Tree with Typescript 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.
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.
In this example we are going to display a digital clock that updates every second. The first render is happening in the server and the date will be `00:00:00`, then the browser will take over and it will start updating the date.
To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.js data fetching methods to get the date in the server and return it as props to the page, and then the browser will hydrate the store and continue updating the date.
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`
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.
## Deploy your own
......@@ -40,34 +48,3 @@ yarn dev
```
Deploy it to the cloud with [ZEIT Now](https://zeit.co/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Notes
This example is a typescript and mobx-state-tree port of the [with-redux](https://github.com/zeit/next.js/tree/master/examples/with-redux) example, by way of the javascript and mobx-state-tree port [with-mobx-state-tree](https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree). Decorator support is activated by adding a `.babelrc` file at the root of the project:
```json
{
"presets": ["next/babel"],
"plugins": ["transform-decorators-legacy"]
}
```
### Rehydrating with server data
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.
## Notes
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.tsx` 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.
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.
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.ts`
The clock, under `components/Clock.tsx`, 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.
The typescript in this `with-mobx-state-tree-typescript` repo differs only slightly from the javascript `with-mobx-state-tree`, with most of the the changes made to avoid warnings and errors when running the code through `tslint` (which can be done via the `npm run tslint` command if desired). To keep this repo simple, the `<styled>` component (which is used by the javascript-based `with-redux` and `with-mobx-state-tree` examples for the clock component) is not used in this repo. The `<styled>` library can be used with typescript but it requires a more complicated interplay between the typescript and babel stages than is needed for most other components and libraries, so it's not included here to keep things simple and broadly applicable.
......@@ -13,4 +13,4 @@ const Clock = props => {
return <div style={divStyle}>{format(new Date(props.lastUpdate))}</div>
}
export { Clock }
export default Clock
import { inject, observer } from 'mobx-react'
import Link from 'next/link'
import React from 'react'
import { IStore } from '../stores/store'
import { Clock } from './Clock'
import { IStore } from '../store'
import Clock from './Clock'
interface IOwnProps {
store?: IStore
......@@ -48,4 +48,4 @@ class SampleComponent extends React.Component<IOwnProps> {
}
}
export { SampleComponent }
export default SampleComponent
......@@ -11,8 +11,8 @@
"mobx-react": "^5.4.3",
"mobx-state-tree": "^3.11.0",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react": "16.13.1",
"react-dom": "16.13.1",
"typescript": "^3.0.1"
},
"devDependencies": {
......
import { Provider } from 'mobx-react'
import { getSnapshot } from 'mobx-state-tree'
import App from 'next/app'
import React from 'react'
import { initializeStore, IStore } from '../stores/store'
import { useStore } from '../store'
interface IOwnProps {
isServer: boolean
initialState: IStore
}
class MyApp extends App {
public static async getInitialProps({ Component, router, ctx }) {
//
// Use getInitialProps as a step in the lifecycle when
// we can initialize our store
//
const isServer = typeof window === 'undefined'
const store = initializeStore(isServer)
//
// Check whether the page being rendered by the App has a
// static getInitialProps method and if so call it
//
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {
initialState: getSnapshot(store),
isServer,
pageProps,
}
}
private store: IStore
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialState)
constructor(props) {
super(props)
this.store = initializeStore(props.isServer, props.initialState) as IStore
}
public render() {
const { Component, pageProps } = this.props
return (
<Provider store={this.store}>
<Component {...pageProps} />
</Provider>
)
}
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
export default MyApp
import React from 'react'
import { SampleComponent } from '../components/SampleComponent'
import SampleComponent from '../components/SampleComponent'
class IndexPage extends React.Component {
public render() {
return <SampleComponent title={'Index Page'} linkTo="/other" />
}
export default () => {
return <SampleComponent title="Index Page" linkTo="/other" />
}
export default IndexPage
import React from 'react'
import { SampleComponent } from '../components/SampleComponent'
import SampleComponent from '../components/SampleComponent'
class OtherPage extends React.Component {
public render() {
return <SampleComponent title={'Other Page'} linkTo="/" />
}
export default () => {
return <SampleComponent title={'Other Page'} linkTo="/" />
}
export default OtherPage
import { getSnapshot } from 'mobx-state-tree'
import SampleComponent from '../components/SampleComponent'
import { initializeStore } from '../store'
export default () => {
return <SampleComponent title={'SSG Page'} linkTo="/" />
}
// If you build and start the app, the date returned here will have the same
// value for all requests, as this method gets executed at build time.
export function getStaticProps() {
const store = initializeStore()
store.update()
return { props: { initialState: getSnapshot(store) } }
}
import { getSnapshot } from 'mobx-state-tree'
import SampleComponent from '../components/SampleComponent'
import { initializeStore } from '../store'
export default () => {
return <SampleComponent title={'SSR Page'} linkTo="/" />
}
// The date returned here will be different for every request that hits the page,
// that is because the page becomes a serverless function instead of being statically
// exported when you use `getServerSideProps` or `getInitialProps`
export function getServerSideProps() {
const store = initializeStore()
store.update()
return { props: { initialState: getSnapshot(store) } }
}
import { useMemo } from 'react'
import {
applySnapshot,
Instance,
......@@ -6,16 +7,15 @@ import {
types,
} from 'mobx-state-tree'
let store: IStore = null as any
let store: IStore | undefined
const Store = types
.model({
foo: types.number,
lastUpdate: types.Date,
light: false,
})
.actions(self => {
let timer
let timer: any
const start = () => {
timer = setInterval(() => {
// mobx-state-tree doesn't allow anonymous callbacks changing data.
......@@ -39,15 +39,23 @@ export type IStore = Instance<typeof Store>
export type IStoreSnapshotIn = SnapshotIn<typeof Store>
export type IStoreSnapshotOut = SnapshotOut<typeof Store>
export const initializeStore = (isServer, snapshot = null) => {
if (isServer) {
store = Store.create({ foo: 6, lastUpdate: Date.now(), light: false })
}
if ((store as any) === null) {
store = Store.create({ foo: 6, lastUpdate: Date.now(), light: false })
}
export function initializeStore(snapshot = null) {
const _store = store ?? Store.create({ lastUpdate: 0 })
// If your page has Next.js data fetching methods that use a Mobx store, it will
// get hydrated here, check `pages/ssg.tsx` and `pages/ssr.tsx` for more details
if (snapshot) {
applySnapshot(store, snapshot)
applySnapshot(_store, snapshot)
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return store
}
export function useStore(initialState: any) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}
# MobX State Tree 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.
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.
In this example we are going to display a digital clock that updates every second. The first render is happening in the server and the date will be `00:00:00`, then the browser will take over and it will start updating the date.
To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.js data fetching methods to get the date in the server and return it as props to the page, and then the browser will hydrate the store and continue updating the date.
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`
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.
## Deploy your own
......@@ -40,32 +48,3 @@ yarn dev
```
Deploy it to the cloud with [ZEIT Now](https://zeit.co/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Notes
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:
```json
{
"presets": ["next/babel"],
"plugins": ["transform-decorators-legacy"]
}
```
### Rehydrating with server data
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.
## Notes
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-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.
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.
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`
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.
import React from 'react'
import { Provider } from 'mobx-react'
import { getSnapshot } from 'mobx-state-tree'
import App from 'next/app'
import { initializeStore } from '../stores/store'
import { useStore } from '../store'
export default class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
//
// Use getInitialProps as a step in the lifecycle when
// we can initialize our store
//
const isServer = typeof window === 'undefined'
const store = initializeStore(isServer)
//
// Check whether the page being rendered by the App has a
// static getInitialProps method and if so call it
//
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {
initialState: getSnapshot(store),
isServer,
pageProps,
}
}
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialState)
constructor(props) {
super(props)
this.store = initializeStore(props.isServer, props.initialState)
}
render() {
const { Component, pageProps } = this.props
return (
<Provider store={this.store}>
<Component {...pageProps} />
</Provider>
)
}
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
import React from 'react'
import SampleComponent from '../components/SampleComponent'
export default () => {
......
import React from 'react'
import SampleComponent from '../components/SampleComponent'
export default () => {
......
import { getSnapshot } from 'mobx-state-tree'
import SampleComponent from '../components/SampleComponent'
import { initializeStore } from '../store'
export default () => {
return <SampleComponent title={'SSG Page'} linkTo="/" />
}
// If you build and start the app, the date returned here will have the same
// value for all requests, as this method gets executed at build time.
export function getStaticProps() {
const store = initializeStore()
store.update()
return { props: { initialState: getSnapshot(store) } }
}
import { getSnapshot } from 'mobx-state-tree'
import SampleComponent from '../components/SampleComponent'
import { initializeStore } from '../store'
export default () => {
return <SampleComponent title={'SSR Page'} linkTo="/" />
}
// The date returned here will be different for every request that hits the page,
// that is because the page becomes a serverless function instead of being statically
// exported when you use `getServerSideProps` or `getInitialProps`
export function getServerSideProps() {
const store = initializeStore()
store.update()
return { props: { initialState: getSnapshot(store) } }
}
import { useMemo } from 'react'
import { types, applySnapshot } from 'mobx-state-tree'
let store = null
let store
const Store = types
.model({
......@@ -29,15 +30,23 @@ const Store = types
return { start, stop, update }
})
export function initializeStore(isServer, snapshot = null) {
if (isServer) {
store = Store.create({ lastUpdate: Date.now() })
}
if (store === null) {
store = Store.create({ lastUpdate: Date.now() })
}
export function initializeStore(snapshot = null) {
const _store = store ?? Store.create({ lastUpdate: 0 })
// If your page has Next.js data fetching methods that use a Mobx store, it will
// get hydrated here, check `pages/ssg.js` and `pages/ssr.js` for more details
if (snapshot) {
applySnapshot(store, snapshot)
applySnapshot(_store, snapshot)
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return store
}
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册