Skip to content

Commit

Permalink
[Examples] Update with-mobx-state-tree examples (#11736)
Browse files Browse the repository at this point in the history
* Updated with-mobx-state-tree

* Updated with-mobx-state-tree-typescript

* minor fix
  • Loading branch information
Luis Alvarez D authored Apr 8, 2020
1 parent 17384fc commit 282f375
Show file tree
Hide file tree
Showing 18 changed files with 188 additions and 228 deletions.
43 changes: 10 additions & 33 deletions examples/with-mobx-state-tree-typescript/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
# 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

Expand Down Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ const Clock = props => {
return <div style={divStyle}>{format(new Date(props.lastUpdate))}</div>
}

export { Clock }
export default Clock
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
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
Expand Down Expand Up @@ -48,4 +48,4 @@ class SampleComponent extends React.Component<IOwnProps> {
}
}

export { SampleComponent }
export default SampleComponent
4 changes: 2 additions & 2 deletions examples/with-mobx-state-tree-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
56 changes: 8 additions & 48 deletions examples/with-mobx-state-tree-typescript/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,12 @@
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
11 changes: 3 additions & 8 deletions examples/with-mobx-state-tree-typescript/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
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
11 changes: 3 additions & 8 deletions examples/with-mobx-state-tree-typescript/pages/other.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
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
17 changes: 17 additions & 0 deletions examples/with-mobx-state-tree-typescript/pages/ssg.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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) } }
}
18 changes: 18 additions & 0 deletions examples/with-mobx-state-tree-typescript/pages/ssr.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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) } }
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo } from 'react'
import {
applySnapshot,
Instance,
Expand All @@ -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.
Expand All @@ -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
}
39 changes: 9 additions & 30 deletions examples/with-mobx-state-tree/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
# 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

Expand Down Expand Up @@ -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.
47 changes: 8 additions & 39 deletions examples/with-mobx-state-tree/pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,12 @@
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>
)
}
1 change: 0 additions & 1 deletion examples/with-mobx-state-tree/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React from 'react'
import SampleComponent from '../components/SampleComponent'

export default () => {
Expand Down
1 change: 0 additions & 1 deletion examples/with-mobx-state-tree/pages/other.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React from 'react'
import SampleComponent from '../components/SampleComponent'

export default () => {
Expand Down
17 changes: 17 additions & 0 deletions examples/with-mobx-state-tree/pages/ssg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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) } }
}
Loading

0 comments on commit 282f375

Please sign in to comment.