-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
47 lines (42 loc) · 1.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React, { Component } from 'react'
import { Provider, connect } from 'react-redux'
import PropTypes from 'prop-types'
const wrapWithProvider = (createStore, PageComponent, cache) => class extends Component {
static propTypes = {
initialState: PropTypes.object
}
static async getInitialProps (ctx) {
const {req} = ctx
const isServer = !!req
if (!cache.store || isServer) {
cache.store = createStore()
}
ctx.store = cache.store
ctx.isServer = isServer
const props = PageComponent.getInitialProps
? await PageComponent.getInitialProps(ctx)
: {}
props.initialState = cache.store.getState()
return props
}
constructor (props) {
super(props)
if (!cache.store) {
cache.store = createStore(props.initialState)
}
}
render () {
return (
<Provider store={cache.store}>
<PageComponent {...this.props} />
</Provider>
)
}
}
export default (createStore) => {
let cache = {}
return (...args) => (PageComponent) => {
PageComponent = connect(...args)(PageComponent)
return wrapWithProvider(createStore, PageComponent, cache)
}
}