mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
mobx-state-tree examples should use _app (#5362)
The mobx-state-tree examples (with and without typescript) pre-dated the next _app class and needed to be updated to use _app for persisting state across client-side navigation transitions. Also removed unneeded custom server class to better keep with the "show one feature per example" style of the next examples folder
This commit is contained in:
parent
1b8bfc70f3
commit
af9214b302
|
@ -1,4 +1,4 @@
|
|||
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree-typescript)
|
||||
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree)
|
||||
|
||||
# MobX State Tree example
|
||||
|
||||
|
@ -70,6 +70,4 @@ The trick here for supporting universal mobx is to separate the cases for the cl
|
|||
|
||||
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.
|
||||
|
||||
As far as how this example differs from the `with-mobx` example, `mobx-state-tree` requires that any changes to the observable data are sent as actions, which are defined on the model in `server.ts`. The snapshot feature, while not very useful in this particular case, makes client-side rehydration of the state amazingly easy. Any changes that are made to the store in `getInitialProps` will be refreshed instantly when that page is loaded on the client.
|
||||
|
||||
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.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import { inject, observer } from "mobx-react";
|
||||
import Link from "next/link";
|
||||
import React from "react";
|
||||
import { IStore } from "../store";
|
||||
import { IStore } from "../stores/store";
|
||||
import { Clock } from "./Clock";
|
||||
|
||||
interface IOwnProps {
|
||||
|
@ -12,7 +12,7 @@ interface IOwnProps {
|
|||
|
||||
@inject("store")
|
||||
@observer
|
||||
class Page extends React.Component<IOwnProps> {
|
||||
class SampleComponent extends React.Component<IOwnProps> {
|
||||
public componentDidMount () {
|
||||
if (!this.props.store) {
|
||||
return;
|
||||
|
@ -29,7 +29,11 @@ class Page extends React.Component<IOwnProps> {
|
|||
|
||||
public render () {
|
||||
if (!this.props.store) {
|
||||
return;
|
||||
return (
|
||||
<div>
|
||||
Store not defined
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
|
@ -43,4 +47,4 @@ class Page extends React.Component<IOwnProps> {
|
|||
}
|
||||
}
|
||||
|
||||
export { Page };
|
||||
export { SampleComponent };
|
|
@ -8,21 +8,21 @@
|
|||
"tslint": "tslint -c tslint.json -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@zeit/next-typescript": "1.1.1",
|
||||
"mobx": "^5.1.2",
|
||||
"mobx-react": "^5.2.8",
|
||||
"mobx-state-tree": "^3.4.0",
|
||||
"@zeit/next-typescript": "1.1.0",
|
||||
"mobx": "5.0.5",
|
||||
"mobx-react": "5.2.5",
|
||||
"mobx-state-tree": "3.2.3",
|
||||
"next": "latest",
|
||||
"react": "^16.5.2",
|
||||
"react-dom": "^16.5.2",
|
||||
"react": "16.4.2",
|
||||
"react-dom": "16.4.2",
|
||||
"typescript": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-decorators": "^7.1.0",
|
||||
"@types/next": "^6.1.4",
|
||||
"@types/react": "^16.4.12",
|
||||
"@babel/plugin-proposal-decorators": "^7.1.2",
|
||||
"tslint": "^5.9.1",
|
||||
"tslint-config-standard": "^8.0.1",
|
||||
"tslint-config-standard": "^7.0.0",
|
||||
"tslint-loader": "^3.5.3",
|
||||
"tslint-react": "^3.4.0"
|
||||
},
|
||||
|
|
55
examples/with-mobx-state-tree-typescript/pages/_app.tsx
Normal file
55
examples/with-mobx-state-tree-typescript/pages/_app.tsx
Normal file
|
@ -0,0 +1,55 @@
|
|||
import { Provider } from "mobx-react";
|
||||
import { getSnapshot } from "mobx-state-tree";
|
||||
import App, { Container } from "next/app";
|
||||
import React from "react";
|
||||
import { initializeStore, IStore } from "../stores/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;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.store = initializeStore(props.isServer, props.initialState) as IStore;
|
||||
}
|
||||
|
||||
public render() {
|
||||
const { Component, pageProps } = this.props;
|
||||
return (
|
||||
<Container>
|
||||
<Provider store={this.store}>
|
||||
<Component {...pageProps} />
|
||||
</Provider>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default MyApp;
|
|
@ -1,35 +1,12 @@
|
|||
import { Provider } from "mobx-react";
|
||||
import { getSnapshot } from "mobx-state-tree";
|
||||
import React from "react";
|
||||
import { Page } from "../components/Page";
|
||||
import { initStore, IStore } from "../store";
|
||||
import { SampleComponent } from "../components/SampleComponent";
|
||||
|
||||
interface IOwnProps {
|
||||
isServer:boolean;
|
||||
initialState:IStore;
|
||||
}
|
||||
|
||||
class Counter extends React.Component<IOwnProps> {
|
||||
public static getInitialProps ({ req }) {
|
||||
const isServer = !!req;
|
||||
const store = initStore(isServer);
|
||||
return { initialState: getSnapshot(store), isServer };
|
||||
}
|
||||
|
||||
private store:IStore;
|
||||
|
||||
constructor (props) {
|
||||
super(props);
|
||||
this.store = initStore(props.isServer, props.initialState) as IStore;
|
||||
}
|
||||
|
||||
public render () {
|
||||
class IndexPage extends React.Component {
|
||||
public render() {
|
||||
return (
|
||||
<Provider store={this.store}>
|
||||
<Page title="Index Page" linkTo="/other" />
|
||||
</Provider>
|
||||
<SampleComponent title={"Index Page"} linkTo="/other" />
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Counter;
|
||||
export default IndexPage;
|
||||
|
|
|
@ -1,35 +1,12 @@
|
|||
import { Provider } from "mobx-react";
|
||||
import { getSnapshot } from "mobx-state-tree";
|
||||
import React from "react";
|
||||
import { Page } from "../components/Page";
|
||||
import { initStore, IStore } from "../store";
|
||||
|
||||
interface IOwnProps {
|
||||
isServer:boolean;
|
||||
initialState:IStore;
|
||||
}
|
||||
|
||||
class Counter extends React.Component<IOwnProps> {
|
||||
public static getInitialProps ({ req }) {
|
||||
const isServer = !!req;
|
||||
const store = initStore(isServer);
|
||||
return { initialState: getSnapshot(store), isServer };
|
||||
}
|
||||
|
||||
private store:IStore;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.store = initStore(props.isServer, props.initialState) as IStore;
|
||||
}
|
||||
import { SampleComponent } from "../components/SampleComponent";
|
||||
|
||||
class OtherPage extends React.Component {
|
||||
public render() {
|
||||
return (
|
||||
<Provider store={this.store}>
|
||||
<Page title="Other Page" linkTo="/" />
|
||||
</Provider>
|
||||
<SampleComponent title={"Other Page"} linkTo="/" />
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Counter;
|
||||
export default OtherPage;
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
import { createServer } from "http";
|
||||
import mobxReact from "mobx-react";
|
||||
import next from "next";
|
||||
import { parse } from "url";
|
||||
|
||||
const envPort = parseInt(process.env.PORT as string, 10) || 3000;
|
||||
const dev = process.env.NODE_ENV !== "production";
|
||||
|
||||
mobxReact.useStaticRendering(true);
|
||||
|
||||
const app = next({ dev });
|
||||
const handle = app.getRequestHandler();
|
||||
|
||||
app.prepare().then(() => {
|
||||
createServer((req, res) => {
|
||||
const parsedUrl = parse(req.url as string, true);
|
||||
handle(req, res, parsedUrl)
|
||||
.catch((error) => { throw(error); });
|
||||
}).listen((port, err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(`> Ready on http://localhost:${port}`);
|
||||
});
|
||||
}).catch((error) => { throw(error); });
|
|
@ -1,9 +1,10 @@
|
|||
import { applySnapshot, Instance, IStateTreeNode, SnapshotIn, SnapshotOut, types } from "mobx-state-tree";
|
||||
import { applySnapshot, Instance, SnapshotIn, SnapshotOut, types } from "mobx-state-tree";
|
||||
|
||||
let store:IStateTreeNode = null as any;
|
||||
let store:IStore = null as any;
|
||||
|
||||
const Store = types
|
||||
.model({
|
||||
foo: types.number,
|
||||
lastUpdate: types.Date,
|
||||
light: false,
|
||||
})
|
||||
|
@ -11,8 +12,8 @@ const Store = types
|
|||
let timer;
|
||||
const start = () => {
|
||||
timer = setInterval(() => {
|
||||
// mobx-state-tree doesn't allow anonymous callbacks changing data
|
||||
// pass off to another action instead (need to cast self as any
|
||||
// mobx-state-tree doesn't allow anonymous callbacks changing data.
|
||||
// Pass off to another action instead (need to cast self as any
|
||||
// because typescript doesn't yet know about the actions we're
|
||||
// adding to self here)
|
||||
(self as any).update();
|
||||
|
@ -32,12 +33,12 @@ type IStore = Instance<typeof Store>;
|
|||
type IStoreSnapshotIn = SnapshotIn<typeof Store>;
|
||||
type IStoreSnapshotOut = SnapshotOut<typeof Store>;
|
||||
|
||||
const initStore = (isServer, snapshot = null) => {
|
||||
const initializeStore = (isServer, snapshot = null) => {
|
||||
if (isServer) {
|
||||
store = Store.create({ lastUpdate: Date.now() });
|
||||
store = Store.create({ foo:6, lastUpdate: Date.now() });
|
||||
}
|
||||
if (store as any === null) {
|
||||
store = Store.create({ lastUpdate: Date.now() });
|
||||
store = Store.create({ foo:6, lastUpdate: Date.now() });
|
||||
}
|
||||
if (snapshot) {
|
||||
applySnapshot(store, snapshot);
|
||||
|
@ -45,4 +46,4 @@ const initStore = (isServer, snapshot = null) => {
|
|||
return store;
|
||||
};
|
||||
|
||||
export { initStore, IStore, IStoreSnapshotIn, IStoreSnapshotOut };
|
||||
export { initializeStore, IStore, IStoreSnapshotIn, IStoreSnapshotOut };
|
|
@ -68,6 +68,4 @@ To pass the initial timestamp from the server to the client we pass it as a prop
|
|||
|
||||
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.
|
||||
|
||||
As far as how this example differs from the `with-mobx` example, `mobx-state-tree` requires that any changes to the observable data are sent as actions, which are defined on the model in `server.js`. The snapshot feature, while not very useful in this particular case, makes client-side rehydration of the state amazingly easy. Any changes that are made to the store in `getInitialProps` will be refreshed instantly when that page is loaded on the client.
|
||||
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.
|
|
@ -3,8 +3,9 @@ import Link from 'next/link'
|
|||
import { inject, observer } from 'mobx-react'
|
||||
import Clock from './Clock'
|
||||
|
||||
@inject('store') @observer
|
||||
class Page extends React.Component {
|
||||
@inject('store')
|
||||
@observer
|
||||
class SampleComponent extends React.Component {
|
||||
componentDidMount () {
|
||||
this.props.store.start()
|
||||
}
|
||||
|
@ -26,4 +27,4 @@ class Page extends React.Component {
|
|||
}
|
||||
}
|
||||
|
||||
export default Page
|
||||
export default SampleComponent
|
|
@ -1,21 +1,21 @@
|
|||
{
|
||||
"name": "with-mobx",
|
||||
"name": "with-mobx-state-tree",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev": "node server.js",
|
||||
"dev": "next",
|
||||
"build": "next build",
|
||||
"start": "NODE_ENV=production node server.js"
|
||||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
"mobx": "^5.1.2",
|
||||
"mobx-react": "^5.2.8",
|
||||
"mobx-state-tree": "^3.4.0",
|
||||
"mobx": "3.3.1",
|
||||
"mobx-react": "^4.0.4",
|
||||
"mobx-state-tree": "1.0.1",
|
||||
"next": "latest",
|
||||
"react": "^16.0.0",
|
||||
"react-dom": "^16.0.0"
|
||||
},
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-decorators": "7.1.0"
|
||||
}
|
||||
"@babel/plugin-proposal-decorators": "^7.1.2"
|
||||
},
|
||||
"license": "ISC"
|
||||
}
|
||||
|
|
45
examples/with-mobx-state-tree/pages/_app.js
Normal file
45
examples/with-mobx-state-tree/pages/_app.js
Normal file
|
@ -0,0 +1,45 @@
|
|||
import React from 'react'
|
||||
import { Provider } from 'mobx-react'
|
||||
import { getSnapshot } from 'mobx-state-tree'
|
||||
import App, { Container } from 'next/app'
|
||||
import { initializeStore } from '../stores/store'
|
||||
|
||||
export default class MyApp extends App {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
constructor (props) {
|
||||
super(props)
|
||||
this.store = initializeStore(props.isServer, props.initialState)
|
||||
}
|
||||
|
||||
render () {
|
||||
const { Component, pageProps } = this.props
|
||||
return (
|
||||
<Container>
|
||||
<Provider store={this.store}>
|
||||
<Component {...pageProps} />
|
||||
</Provider>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
}
|
|
@ -1,26 +1,8 @@
|
|||
import React from 'react'
|
||||
import { Provider } from 'mobx-react'
|
||||
import { getSnapshot } from 'mobx-state-tree'
|
||||
import { initStore } from '../store'
|
||||
import Page from '../components/Page'
|
||||
import SampleComponent from '../components/SampleComponent'
|
||||
|
||||
export default class Counter extends React.Component {
|
||||
static getInitialProps ({ req }) {
|
||||
const isServer = !!req
|
||||
const store = initStore(isServer)
|
||||
return { initialState: getSnapshot(store), isServer }
|
||||
}
|
||||
|
||||
constructor (props) {
|
||||
super(props)
|
||||
this.store = initStore(props.isServer, props.initialState)
|
||||
}
|
||||
|
||||
render () {
|
||||
return (
|
||||
<Provider store={this.store}>
|
||||
<Page title='Index Page' linkTo='/other' />
|
||||
</Provider>
|
||||
)
|
||||
}
|
||||
export default () => {
|
||||
return (
|
||||
<SampleComponent title='Index Page' linkTo='/other' />
|
||||
)
|
||||
}
|
||||
|
|
|
@ -1,26 +1,8 @@
|
|||
import React from 'react'
|
||||
import { Provider } from 'mobx-react'
|
||||
import { getSnapshot } from 'mobx-state-tree'
|
||||
import { initStore } from '../store'
|
||||
import Page from '../components/Page'
|
||||
import SampleComponent from '../components/SampleComponent'
|
||||
|
||||
export default class Counter extends React.Component {
|
||||
static getInitialProps ({ req }) {
|
||||
const isServer = !!req
|
||||
const store = initStore(isServer)
|
||||
return { initialState: getSnapshot(store), isServer }
|
||||
}
|
||||
|
||||
constructor (props) {
|
||||
super(props)
|
||||
this.store = initStore(props.isServer, props.initialState)
|
||||
}
|
||||
|
||||
render () {
|
||||
return (
|
||||
<Provider store={this.store}>
|
||||
<Page title='Other Page' linkTo='/' />
|
||||
</Provider>
|
||||
)
|
||||
}
|
||||
export default () => {
|
||||
return (
|
||||
<SampleComponent title={'Other Page'} linkTo='/' />
|
||||
)
|
||||
}
|
||||
|
|
|
@ -1,21 +0,0 @@
|
|||
const port = parseInt(process.env.PORT, 10) || 3000
|
||||
const dev = process.env.NODE_ENV !== 'production'
|
||||
|
||||
const { createServer } = require('http')
|
||||
const { parse } = require('url')
|
||||
const next = require('next')
|
||||
const mobxReact = require('mobx-react')
|
||||
const app = next({ dev })
|
||||
const handle = app.getRequestHandler()
|
||||
|
||||
mobxReact.useStaticRendering(true)
|
||||
|
||||
app.prepare().then(() => {
|
||||
createServer((req, res) => {
|
||||
const parsedUrl = parse(req.url, true)
|
||||
handle(req, res, parsedUrl)
|
||||
}).listen(port, err => {
|
||||
if (err) throw err
|
||||
console.log(`> Ready on http://localhost:${port}`)
|
||||
})
|
||||
})
|
|
@ -29,7 +29,7 @@ const Store = types
|
|||
return { start, stop, update }
|
||||
})
|
||||
|
||||
export function initStore (isServer, snapshot = null) {
|
||||
export function initializeStore (isServer, snapshot = null) {
|
||||
if (isServer) {
|
||||
store = Store.create({ lastUpdate: Date.now() })
|
||||
}
|
Loading…
Reference in a new issue