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-mobx/pages/_app.js
Már Örlygsson 766d7d5fe4 Run initializeStore() only once per route on server (#5644)
On the server `props.initialMobxState` received by the `constructor` is a fully functioning mobx store that was instantiated by `getInitialProps()` only a few ticks earlier.
Thus, creating a new instance is unneccessary.

In the browser, however, `props.initialMobxState` is a hydrated plain object and thus the store needs to be initialized.
2018-11-20 15:53:28 +01:00

42 lines
1.2 KiB
JavaScript

import App, {Container} from 'next/app'
import React from 'react'
import { initializeStore } from '../store'
import { Provider } from 'mobx-react'
class MyMobxApp extends App {
static async getInitialProps(appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const mobxStore = initializeStore()
// Provide the store to getInitialProps of pages
appContext.ctx.mobxStore = mobxStore
let appProps = await App.getInitialProps(appContext)
return {
...appProps,
initialMobxState: mobxStore
};
}
constructor(props) {
super(props)
const isServer = typeof window === 'undefined'
this.mobxStore = isServer ?
props.initialMobxState:
initializeStore(props.initialMobxState)
}
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Provider store={this.mobxStore}>
<Component {...pageProps} />
</Provider>
</Container>
);
}
}
export default MyMobxApp