1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

improve with-unstated example (#5998)

improve the example so that it can preserve unstated from server to client unstated
This commit is contained in:
tylim 2019-01-06 23:58:06 +08:00 committed by Tim Neutkens
parent ba95f7541c
commit 5d8ae4456e
4 changed files with 33 additions and 7 deletions

View file

@ -2,7 +2,7 @@ import * as React from 'react'
import Link from 'next/link'
export default class About extends React.Component {
state = { name: '' };
state = { name: '' }
async componentDidMount () {
const name = await window.getName()

View file

@ -43,5 +43,4 @@ now
This example shows how to integrate Unstated in Next.js. For more info about Unstated you can visit [here](https://github.com/jamiebuilds/unstated). The example is basically same as [redux example](https://github.com/zeit/next.js/tree/canary/examples/with-redux).
This example also shows how to share state within different page, you can expect the same state for Counter when switching between Index and About.
The "counter" shows you how to preserve state from server to client and share the state within different page, you can expect the same state for "counter" when switching between Index and About page, observe that "counter" behaves differently from the "clock" example.

View file

@ -16,4 +16,13 @@ export default class CounterContainer extends Container {
reset = () => {
this.setState({ count: 0 })
}
// this two methods are not setState as they work only before rendering
initState = count => {
this.state = { count }
}
resetState = () => {
this.initState(0)
}
}
export const counterStore = new CounterContainer()

View file

@ -1,16 +1,34 @@
import App, { Container } from 'next/app'
import React from 'react'
import { Provider } from 'unstated'
import { CounterContainer } from '../containers'
const counter = new CounterContainer()
import { counterStore } from '../containers/CounterContainer'
class MyApp extends App {
static async getInitialProps () {
// do your server state here
if (!process.browser) {
// reset state for each request
counterStore.resetState()
// process state, in this case counter start with 999
counterStore.initState(999)
return { serverState: counterStore.state }
} else {
return {}
}
}
constructor (props) {
super(props)
// pass the state to client store
// serverState will be reset when client navigate with Link
if (process.browser) {
counterStore.initState(props.serverState.count)
}
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Provider inject={[counter]}>
<Provider inject={[counterStore]}>
<Component {...pageProps} />
</Provider>
</Container>