diff --git a/examples/with-mobx-state-tree-typescript/README.md b/examples/with-mobx-state-tree-typescript/README.md index 5d3d818844d14..8d9bc16d8b72f 100644 --- a/examples/with-mobx-state-tree-typescript/README.md +++ b/examples/with-mobx-state-tree-typescript/README.md @@ -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 @@ -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 ` 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 `` 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 `` 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. diff --git a/examples/with-mobx-state-tree-typescript/components/Clock.tsx b/examples/with-mobx-state-tree-typescript/components/Clock.tsx index bac88c77a8bb7..10cd0cf8ff738 100644 --- a/examples/with-mobx-state-tree-typescript/components/Clock.tsx +++ b/examples/with-mobx-state-tree-typescript/components/Clock.tsx @@ -13,4 +13,4 @@ const Clock = props => { return
{format(new Date(props.lastUpdate))}
} -export { Clock } +export default Clock diff --git a/examples/with-mobx-state-tree-typescript/components/SampleComponent.tsx b/examples/with-mobx-state-tree-typescript/components/SampleComponent.tsx index 58da345264e27..f08277c21006d 100644 --- a/examples/with-mobx-state-tree-typescript/components/SampleComponent.tsx +++ b/examples/with-mobx-state-tree-typescript/components/SampleComponent.tsx @@ -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 @@ -48,4 +48,4 @@ class SampleComponent extends React.Component { } } -export { SampleComponent } +export default SampleComponent diff --git a/examples/with-mobx-state-tree-typescript/package.json b/examples/with-mobx-state-tree-typescript/package.json index 43e099db3f2ba..d0830a379c8ac 100644 --- a/examples/with-mobx-state-tree-typescript/package.json +++ b/examples/with-mobx-state-tree-typescript/package.json @@ -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": { diff --git a/examples/with-mobx-state-tree-typescript/pages/_app.tsx b/examples/with-mobx-state-tree-typescript/pages/_app.tsx index 80c8958440d76..e75b81d85556a 100644 --- a/examples/with-mobx-state-tree-typescript/pages/_app.tsx +++ b/examples/with-mobx-state-tree-typescript/pages/_app.tsx @@ -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 ( - - - - ) - } + return ( + + + + ) } - -export default MyApp diff --git a/examples/with-mobx-state-tree-typescript/pages/index.tsx b/examples/with-mobx-state-tree-typescript/pages/index.tsx index 567bd0938ad7a..923af31f2ea7f 100644 --- a/examples/with-mobx-state-tree-typescript/pages/index.tsx +++ b/examples/with-mobx-state-tree-typescript/pages/index.tsx @@ -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 - } +export default () => { + return } - -export default IndexPage diff --git a/examples/with-mobx-state-tree-typescript/pages/other.tsx b/examples/with-mobx-state-tree-typescript/pages/other.tsx index dc6033bb1a1fd..b131e2f904b86 100644 --- a/examples/with-mobx-state-tree-typescript/pages/other.tsx +++ b/examples/with-mobx-state-tree-typescript/pages/other.tsx @@ -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 - } +export default () => { + return } - -export default OtherPage diff --git a/examples/with-mobx-state-tree-typescript/pages/ssg.tsx b/examples/with-mobx-state-tree-typescript/pages/ssg.tsx new file mode 100644 index 0000000000000..d1a62193f92ec --- /dev/null +++ b/examples/with-mobx-state-tree-typescript/pages/ssg.tsx @@ -0,0 +1,17 @@ +import { getSnapshot } from 'mobx-state-tree' +import SampleComponent from '../components/SampleComponent' +import { initializeStore } from '../store' + +export default () => { + return +} + +// 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) } } +} diff --git a/examples/with-mobx-state-tree-typescript/pages/ssr.tsx b/examples/with-mobx-state-tree-typescript/pages/ssr.tsx new file mode 100644 index 0000000000000..275e171c8b63e --- /dev/null +++ b/examples/with-mobx-state-tree-typescript/pages/ssr.tsx @@ -0,0 +1,18 @@ +import { getSnapshot } from 'mobx-state-tree' +import SampleComponent from '../components/SampleComponent' +import { initializeStore } from '../store' + +export default () => { + return +} + +// 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) } } +} diff --git a/examples/with-mobx-state-tree-typescript/stores/store.ts b/examples/with-mobx-state-tree-typescript/store.ts similarity index 57% rename from examples/with-mobx-state-tree-typescript/stores/store.ts rename to examples/with-mobx-state-tree-typescript/store.ts index 345c7863b7a18..e30e00e4f953e 100644 --- a/examples/with-mobx-state-tree-typescript/stores/store.ts +++ b/examples/with-mobx-state-tree-typescript/store.ts @@ -1,3 +1,4 @@ +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 export type IStoreSnapshotIn = SnapshotIn export type IStoreSnapshotOut = SnapshotOut -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 } diff --git a/examples/with-mobx-state-tree/README.md b/examples/with-mobx-state-tree/README.md index 2a0721a5f0d4c..e0f8c786c9ad2 100644 --- a/examples/with-mobx-state-tree/README.md +++ b/examples/with-mobx-state-tree/README.md @@ -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 @@ -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 ` 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. diff --git a/examples/with-mobx-state-tree/pages/_app.js b/examples/with-mobx-state-tree/pages/_app.js index 8f0a292e99fcc..e75b81d85556a 100644 --- a/examples/with-mobx-state-tree/pages/_app.js +++ b/examples/with-mobx-state-tree/pages/_app.js @@ -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 ( - - - - ) - } + return ( + + + + ) } diff --git a/examples/with-mobx-state-tree/pages/index.js b/examples/with-mobx-state-tree/pages/index.js index 8cde1fd6a0450..923af31f2ea7f 100644 --- a/examples/with-mobx-state-tree/pages/index.js +++ b/examples/with-mobx-state-tree/pages/index.js @@ -1,4 +1,3 @@ -import React from 'react' import SampleComponent from '../components/SampleComponent' export default () => { diff --git a/examples/with-mobx-state-tree/pages/other.js b/examples/with-mobx-state-tree/pages/other.js index de50e65151ced..b131e2f904b86 100644 --- a/examples/with-mobx-state-tree/pages/other.js +++ b/examples/with-mobx-state-tree/pages/other.js @@ -1,4 +1,3 @@ -import React from 'react' import SampleComponent from '../components/SampleComponent' export default () => { diff --git a/examples/with-mobx-state-tree/pages/ssg.js b/examples/with-mobx-state-tree/pages/ssg.js new file mode 100644 index 0000000000000..d1a62193f92ec --- /dev/null +++ b/examples/with-mobx-state-tree/pages/ssg.js @@ -0,0 +1,17 @@ +import { getSnapshot } from 'mobx-state-tree' +import SampleComponent from '../components/SampleComponent' +import { initializeStore } from '../store' + +export default () => { + return +} + +// 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) } } +} diff --git a/examples/with-mobx-state-tree/pages/ssr.js b/examples/with-mobx-state-tree/pages/ssr.js new file mode 100644 index 0000000000000..275e171c8b63e --- /dev/null +++ b/examples/with-mobx-state-tree/pages/ssr.js @@ -0,0 +1,18 @@ +import { getSnapshot } from 'mobx-state-tree' +import SampleComponent from '../components/SampleComponent' +import { initializeStore } from '../store' + +export default () => { + return +} + +// 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) } } +} diff --git a/examples/with-mobx-state-tree/store.js b/examples/with-mobx-state-tree/store.js new file mode 100644 index 0000000000000..81d22b06ddfdf --- /dev/null +++ b/examples/with-mobx-state-tree/store.js @@ -0,0 +1,52 @@ +import { useMemo } from 'react' +import { types, applySnapshot } from 'mobx-state-tree' + +let store + +const Store = types + .model({ + lastUpdate: types.Date, + light: false, + }) + .actions(self => { + let timer + function start() { + timer = setInterval(() => { + // mobx-state-tree doesn't allow anonymous callbacks changing data + // pass off to another action instead + self.update() + }, 1000) + } + + function update() { + self.lastUpdate = Date.now() + self.light = true + } + + function stop() { + clearInterval(timer) + } + + return { start, stop, update } + }) + +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) + } + // 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 +} diff --git a/examples/with-mobx-state-tree/stores/store.js b/examples/with-mobx-state-tree/stores/store.js deleted file mode 100644 index 681b7c25b1cfe..0000000000000 --- a/examples/with-mobx-state-tree/stores/store.js +++ /dev/null @@ -1,43 +0,0 @@ -import { types, applySnapshot } from 'mobx-state-tree' - -let store = null - -const Store = types - .model({ - lastUpdate: types.Date, - light: false, - }) - .actions(self => { - let timer - function start() { - timer = setInterval(() => { - // mobx-state-tree doesn't allow anonymous callbacks changing data - // pass off to another action instead - self.update() - }, 1000) - } - - function update() { - self.lastUpdate = Date.now() - self.light = true - } - - function stop() { - clearInterval(timer) - } - - 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() }) - } - if (snapshot) { - applySnapshot(store, snapshot) - } - return store -}