rsnext/examples/with-mobx/pages/_app.js
Már Örlygsson 420f74c867 examples/with-mobx : Fix and simplify (#5537)
I spent far too much time fiddling with this example project before realizing it contained a bug in the store initialization logic and it was a bit more complex than it needed to be.

* The custom server was not needed
* The store-initialization did effectively the same thing twice for no reason
* And wrapping MyApp component in a HOC was wholly unnecessary indirection

My changes are split into four discrete commits for clarity.
2018-11-06 10:18:26 +01:00

38 lines
1.1 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)
this.mobxStore = initializeStore(props.initialMobxState)
}
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Provider store={this.mobxStore}>
<Component {...pageProps} />
</Provider>
</Container>
);
}
}
export default MyMobxApp