2018-06-13 12:40:59 +00:00
|
|
|
import React from 'react'
|
2018-05-07 13:03:54 +00:00
|
|
|
import {initializeStore} from '../store'
|
|
|
|
|
|
|
|
const isServer = typeof window === 'undefined'
|
|
|
|
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
|
|
|
|
|
2018-08-20 06:31:24 +00:00
|
|
|
function getOrCreateStore (initialState) {
|
2018-05-07 13:03:54 +00:00
|
|
|
// Always make a new store if server, otherwise state is shared between requests
|
|
|
|
if (isServer) {
|
|
|
|
return initializeStore(initialState)
|
|
|
|
}
|
|
|
|
|
2018-06-13 12:40:59 +00:00
|
|
|
// Create store if unavailable on the client and set it on the window object
|
2018-05-07 13:03:54 +00:00
|
|
|
if (!window[__NEXT_REDUX_STORE__]) {
|
|
|
|
window[__NEXT_REDUX_STORE__] = initializeStore(initialState)
|
|
|
|
}
|
|
|
|
return window[__NEXT_REDUX_STORE__]
|
|
|
|
}
|
|
|
|
|
|
|
|
export default (App) => {
|
2018-06-13 12:40:59 +00:00
|
|
|
return class AppWithRedux extends React.Component {
|
2018-05-07 13:03:54 +00:00
|
|
|
static async getInitialProps (appContext) {
|
2018-06-13 12:40:59 +00:00
|
|
|
// Get or Create the store with `undefined` as initialState
|
|
|
|
// This allows you to set a custom default initialState
|
2018-05-07 13:03:54 +00:00
|
|
|
const reduxStore = getOrCreateStore()
|
2018-05-15 07:49:07 +00:00
|
|
|
|
2018-05-07 13:03:54 +00:00
|
|
|
// Provide the store to getInitialProps of pages
|
|
|
|
appContext.ctx.reduxStore = reduxStore
|
|
|
|
|
|
|
|
let appProps = {}
|
2018-06-13 12:40:59 +00:00
|
|
|
if (typeof App.getInitialProps === 'function') {
|
2018-08-20 06:31:24 +00:00
|
|
|
appProps = await App.getInitialProps(appContext)
|
2018-05-07 13:03:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...appProps,
|
|
|
|
initialReduxState: reduxStore.getState()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-20 06:31:24 +00:00
|
|
|
constructor (props) {
|
2018-05-07 13:03:54 +00:00
|
|
|
super(props)
|
|
|
|
this.reduxStore = getOrCreateStore(props.initialReduxState)
|
|
|
|
}
|
|
|
|
|
2018-08-20 06:31:24 +00:00
|
|
|
render () {
|
2018-05-07 13:03:54 +00:00
|
|
|
return <App {...this.props} reduxStore={this.reduxStore} />
|
|
|
|
}
|
|
|
|
}
|
2018-05-15 07:49:07 +00:00
|
|
|
}
|