1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/with-unstated/pages/_app.js
tylim 5d8ae4456e improve with-unstated example (#5998)
improve the example so that it can preserve unstated from server to client unstated
2019-01-06 16:58:06 +01:00

40 lines
1 KiB
JavaScript

import App, { Container } from 'next/app'
import React from 'react'
import { Provider } from 'unstated'
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={[counterStore]}>
<Component {...pageProps} />
</Provider>
</Container>
)
}
}
export default MyApp