Unverified Commit 155a4d5e authored by Henrik Wenz's avatar Henrik Wenz Committed by GitHub

[Docs] Remove legacy mobx example (#40304)

## Info

This PR merges with-mobx-lite into with-mobx. After that we will migrate `with-mobx` to typescript.

## Context

As discussed in https://github.com/vercel/next.js/pull/40302#issuecomment-1239238966 we are going to merge the mobx examples.

#40302

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent eadaca78
{
"presets": ["next/babel"],
"plugins": [["@babel/plugin-proposal-class-properties", { "loose": false }]]
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# MobX V6 with Mobx React Lite # MobX React Light
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. **Note:** This example has been moved to [examples/with-mobx](../with-mobx/)
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.
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`.
Page.js component is using the clock store to start and stop the store clock.
Clock.js component is using the clock store to read the time.
StoreProvider.js component is used to instantiate the `Store` both on the server and on the client.
Both components are using a custom hook `useStore` to pull in the `Store` from the provider.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-mobx-react-lite)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mobx-react-lite&project-name=with-mobx-react-lite&repository-name=with-mobx-react-lite)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-mobx-react-lite with-mobx-react-lite-app
```
```bash
yarn create next-app --example with-mobx-react-lite with-mobx-react-lite-app
```
```bash
pnpm create next-app --example with-mobx-react-lite with-mobx-react-lite-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import { observer } from 'mobx-react-lite'
import { useStore } from './StoreProvider'
const Clock = observer(function Clock(props) {
// use store from the store context
const store = useStore()
return (
<div className={store.light ? 'light' : ''}>
{store.timeString}
<style jsx>{`
div {
padding: 15px;
color: #82fa58;
display: inline-block;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
})
export default Clock
import { observer } from 'mobx-react-lite'
import Link from 'next/link'
import { useEffect } from 'react'
import Clock from './Clock'
import { useStore } from './StoreProvider'
const Page = observer(function Page(props) {
// use store from the store context
const store = useStore()
//start the clock when the component is mounted
useEffect(() => {
store.start()
// stop the clock when the component unmounts
return () => {
store.stop()
}
}, [store])
return (
<div>
<h1>{props.title}</h1>
<Clock />
<nav>
<Link href={props.linkTo}>
<a>Navigate</a>
</Link>
</nav>
</div>
)
})
export default Page
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"mobx": "^6.0.3",
"mobx-react-lite": "^3.1.5",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/core": "7.14.5",
"@babel/plugin-proposal-class-properties": "^7.1.0"
}
}
import { StoreProvider } from '../components/StoreProvider'
export default function App({ Component, pageProps }) {
return (
<StoreProvider {...pageProps}>
<Component {...pageProps} />
</StoreProvider>
)
}
import Page from '../components/Page'
export default function Index() {
return <Page title="Index Page" linkTo="/other" />
}
import Page from '../components/Page'
export default function Other() {
return <Page title="Other Page" linkTo="/" />
}
import Page from '../components/Page'
export default function SSG() {
return <Page title="Index Page" linkTo="/other" />
}
// 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() {
return { props: { initialState: { lastUpdate: Date.now() } } }
}
import Page from '../components/Page'
export default function SSR() {
return <Page title="Index Page" linkTo="/other" />
}
// 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() {
return { props: { initialState: { lastUpdate: Date.now() } } }
}
import { action, observable, computed, runInAction, makeObservable } from 'mobx'
import { enableStaticRendering } from 'mobx-react-lite'
enableStaticRendering(typeof window === 'undefined')
export class Store {
lastUpdate = 0
light = false
constructor() {
makeObservable(this, {
lastUpdate: observable,
light: observable,
start: action,
hydrate: action,
timeString: computed,
})
}
start = () => {
this.timer = setInterval(() => {
runInAction(() => {
this.lastUpdate = Date.now()
this.light = true
})
}, 1000)
}
get timeString() {
const pad = (n) => (n < 10 ? `0${n}` : n)
const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(
t.getUTCSeconds()
)}`
return format(new Date(this.lastUpdate))
}
stop = () => clearInterval(this.timer)
hydrate = (data) => {
if (!data) return
this.lastUpdate = data.lastUpdate !== null ? data.lastUpdate : Date.now()
this.light = !!data.light
}
}
{
"presets": ["next/babel"],
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": false }]
]
}
# MobX example # MobX V6 with Mobx React Lite
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. 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.
...@@ -8,28 +8,34 @@ To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.j ...@@ -8,28 +8,34 @@ To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.j
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 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. Page.js component is using the clock store to start and stop the store clock.
Clock.js component is using the clock store to read the time.
StoreProvider.js component is used to instantiate the `Store` both on the server and on the client.
Both components are using a custom hook `useStore` to pull in the `Store` from the provider.
## Deploy your own ## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-mobx) Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-mobx-react-lite)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mobx&project-name=with-mobx&repository-name=with-mobx) [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mobx-react-lite&project-name=with-mobx-react-lite&repository-name=with-mobx-react-lite)
## How to use ## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash ```bash
npx create-next-app --example with-mobx with-mobx-app npx create-next-app --example with-mobx-react-lite with-mobx-react-lite-app
``` ```
```bash ```bash
yarn create next-app --example with-mobx with-mobx-app yarn create next-app --example with-mobx-react-lite with-mobx-react-lite-app
``` ```
```bash ```bash
pnpm create next-app --example with-mobx with-mobx-app pnpm create next-app --example with-mobx-react-lite with-mobx-react-lite-app
``` ```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import { observer } from 'mobx-react' import { observer } from 'mobx-react-lite'
const Clock = observer((props) => { import { useStore } from './StoreProvider'
const Clock = observer(function Clock(props) {
// use store from the store context
const store = useStore()
return ( return (
<div className={props.light ? 'light' : ''}> <div className={store.light ? 'light' : ''}>
{props.timeString} {store.timeString}
<style jsx>{` <style jsx>{`
div { div {
padding: 15px; padding: 15px;
...@@ -19,4 +24,5 @@ const Clock = observer((props) => { ...@@ -19,4 +24,5 @@ const Clock = observer((props) => {
</div> </div>
) )
}) })
export default Clock export default Clock
import React from 'react' import { observer } from 'mobx-react-lite'
import Link from 'next/link' import Link from 'next/link'
import { inject, observer } from 'mobx-react' import { useEffect } from 'react'
import Clock from './Clock' import Clock from './Clock'
import { useStore } from './StoreProvider'
@inject('store') const Page = observer(function Page(props) {
@observer // use store from the store context
class Page extends React.Component { const store = useStore()
componentDidMount() {
this.props.store.start()
}
componentWillUnmount() { //start the clock when the component is mounted
this.props.store.stop() useEffect(() => {
} store.start()
render() { // stop the clock when the component unmounts
return ( return () => {
<div> store.stop()
<h1>{this.props.title}</h1> }
<Clock }, [store])
timeString={this.props.store.timeString}
light={this.props.store.light} return (
/> <div>
<nav> <h1>{props.title}</h1>
<Link href={this.props.linkTo}> <Clock />
<a>Navigate</a> <nav>
</Link> <Link href={props.linkTo}>
</nav> <a>Navigate</a>
</div> </Link>
) </nav>
} </div>
} )
})
export default Page export default Page
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"mobx": "^6.0.1", "mobx": "^6.6.1",
"mobx-react": "^7.0.0", "mobx-react-lite": "^3.4.0",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "^18.2.0",
"react-dom": "^17.0.2" "react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/core": "7.14.5",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/plugin-proposal-decorators": "^7.1.0"
} }
} }
import { Provider } from 'mobx-react' import { StoreProvider } from '../components/StoreProvider'
import { useStore } from '../store'
export default function App({ Component, pageProps }) { export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialState)
return ( return (
<Provider store={store}> <StoreProvider {...pageProps}>
<Component {...pageProps} /> <Component {...pageProps} />
</Provider> </StoreProvider>
) )
} }
import { action, observable, computed, runInAction, makeObservable } from 'mobx' import { action, observable, computed, runInAction, makeObservable } from 'mobx'
import { enableStaticRendering } from 'mobx-react' import { enableStaticRendering } from 'mobx-react-lite'
import { useMemo } from 'react'
// eslint-disable-next-line react-hooks/rules-of-hooks
enableStaticRendering(typeof window === 'undefined') enableStaticRendering(typeof window === 'undefined')
let store export class Store {
lastUpdate = 0
light = false
class Store {
constructor() { constructor() {
makeObservable(this) makeObservable(this, {
lastUpdate: observable,
light: observable,
start: action,
hydrate: action,
timeString: computed,
})
} }
@observable lastUpdate = 0 start = () => {
@observable light = false
@action start = () => {
this.timer = setInterval(() => { this.timer = setInterval(() => {
runInAction(() => { runInAction(() => {
this.lastUpdate = Date.now() this.lastUpdate = Date.now()
...@@ -23,7 +26,7 @@ class Store { ...@@ -23,7 +26,7 @@ class Store {
}, 1000) }, 1000)
} }
@computed get timeString() { get timeString() {
const pad = (n) => (n < 10 ? `0${n}` : n) const pad = (n) => (n < 10 ? `0${n}` : n)
const format = (t) => const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad( `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(
...@@ -34,31 +37,10 @@ class Store { ...@@ -34,31 +37,10 @@ class Store {
stop = () => clearInterval(this.timer) stop = () => clearInterval(this.timer)
@action hydrate = (data) => { hydrate = (data) => {
if (!data) return if (!data) return
this.lastUpdate = data.lastUpdate !== null ? data.lastUpdate : Date.now() this.lastUpdate = data.lastUpdate !== null ? data.lastUpdate : Date.now()
this.light = !!data.light this.light = !!data.light
} }
} }
function initializeStore(initialData = null) {
const _store = store ?? new Store()
// 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 (initialData) {
_store.hydrate(initialData)
}
// 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% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment