Unverified Commit 2b9268a9 authored by Henrik Wenz's avatar Henrik Wenz Committed by GitHub

[Docs] Merge with-mobx-state-tree with with-mobx-state-tree-typescript example (#40306)

## Changes

see commits

## 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 b85fceac
{
"presets": ["next/babel"],
"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}
# 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 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.
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
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-state-tree-typescript)
[![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-state-tree-typescript&project-name=with-mobx-state-tree-typescript&repository-name=with-mobx-state-tree-typescript)
## 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-state-tree-typescript with-mobx-state-tree-typescript-app
```
```bash
yarn create next-app --example with-mobx-state-tree-typescript with-mobx-state-tree-typescript-app
```
```bash
pnpm create next-app --example with-mobx-state-tree-typescript with-mobx-state-tree-typescript-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)).
**Note:** This example has been moved to [examples/with-mobx-state-tree](../with-mobx-state-tree/)
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"mobx": "^5.9.0",
"mobx-react": "^5.4.3",
"mobx-react-lite": "^2.0.7",
"mobx-state-tree": "^3.11.0",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"typescript": "^3.0.1"
},
"devDependencies": {
"@babel/core": "7.14.3",
"@babel/plugin-proposal-decorators": "^7.3.0",
"@types/node": "^14.0.23",
"@types/react": "^16.4.12"
}
}
{
"presets": ["next/babel"],
"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}
# 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.
......@@ -12,24 +12,24 @@ The clock, under `components/Clock.js`, has access to the state using the `injec
## 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-state-tree)
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-state-tree-typescript)
[![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-state-tree&project-name=with-mobx-state-tree&repository-name=with-mobx-state-tree)
[![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-state-tree-typescript&project-name=with-mobx-state-tree-typescript&repository-name=with-mobx-state-tree-typescript)
## 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-state-tree with-mobx-state-tree-app
npx create-next-app --example with-mobx-state-tree-typescript with-mobx-state-tree-typescript-app
```
```bash
yarn create next-app --example with-mobx-state-tree with-mobx-state-tree-app
yarn create next-app --example with-mobx-state-tree-typescript with-mobx-state-tree-typescript-app
```
```bash
pnpm create next-app --example with-mobx-state-tree with-mobx-state-tree-app
pnpm create next-app --example with-mobx-state-tree-typescript with-mobx-state-tree-typescript-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)).
export default 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)
import React from 'react'
import Link from 'next/link'
import { inject, observer } from 'mobx-react'
import Clock from './Clock'
@inject('store')
@observer
class SampleComponent extends React.Component {
componentDidMount() {
this.props.store.start()
}
componentWillUnmount() {
this.props.store.stop()
}
render() {
return (
<div>
<h1>{this.props.title}</h1>
<Clock
lastUpdate={this.props.store.lastUpdate}
light={this.props.store.light}
/>
<nav>
<Link href={this.props.linkTo}>
<a>Navigate</a>
</Link>
</nav>
</div>
)
}
}
export default SampleComponent
......@@ -6,15 +6,17 @@
"start": "next start"
},
"dependencies": {
"mobx": "3.3.1",
"mobx-react": "^4.0.4",
"mobx-state-tree": "1.0.1",
"mobx": "^6.6.1",
"mobx-react": "^7.5.2",
"mobx-react-lite": "^3.4.0",
"mobx-state-tree": "^5.1.6",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/core": "7.14.5",
"@babel/plugin-proposal-decorators": "^7.1.2"
"@types/node": "^18.7.15",
"@types/react": "^18.0.18",
"typescript": "^4.8.2"
}
}
import { Provider } from 'mobx-react'
import { useStore } from '../store'
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialState)
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
import SampleComponent from '../components/SampleComponent'
export default function Home() {
return <SampleComponent title="Index Page" linkTo="/other" />
}
import SampleComponent from '../components/SampleComponent'
export default function Other() {
return <SampleComponent title={'Other Page'} linkTo="/" />
}
import { getSnapshot } from 'mobx-state-tree'
import SampleComponent from '../components/SampleComponent'
import { initializeStore } from '../store'
export default function Ssg() {
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 function Ssr() {
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
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
}
......@@ -13,7 +13,7 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"experimentalDecorators": true
"incremental": true
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
......
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