rsnext/examples/with-rematch/shared/withRematch.js
Natalie Marleny 0846ed2df7 fix:7271 with-rematch - make sever rendered user list persist (#7308)
* Simplify with-rematch example by removing unnecessary code

Functionality has remained the same.

* Use correct store initialization (from with-redux)

Previous implementation didn't initialize the correctly. Since the `with-redux` example implements this correctly, this solution has been copied over almost verbatim.
2019-05-12 11:13:02 +02:00

51 lines
1.4 KiB
JavaScript

import React from 'react'
import { checkServer } from './utils'
import { initializeStore } from './store'
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
function getOrCreateStore (initialState) {
// Always make a new store if server, otherwise state is shared between requests
if (checkServer()) {
return initializeStore(initialState)
}
// Create store if unavailable on the client and set it on the window object
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = initializeStore(initialState)
}
return window[__NEXT_REDUX_STORE__]
}
export default App => {
return class AppWithRematch extends React.Component {
static async getInitialProps (appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const reduxStore = getOrCreateStore()
// Provide the store to getInitialProps of pages
appContext.ctx.reduxStore = reduxStore
let appProps = {}
if (typeof App.getInitialProps === 'function') {
appProps = await App.getInitialProps(appContext)
}
return {
...appProps,
initialReduxState: reduxStore.getState()
}
}
constructor (props) {
super(props)
this.reduxStore = getOrCreateStore(props.initialReduxState)
}
render () {
return <App {...this.props} reduxStore={this.reduxStore} />
}
}
}