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-refnux/helpers/withRefnux.js

42 lines
1.3 KiB
JavaScript
Raw Normal View History

import { Provider } from 'refnux'
2017-02-21 04:13:05 +00:00
import getStore from './getStore'
// The `withRefnux` "decorator"
// - wraps the given Component in a refnux Provider component
// - creates a `store` for the Provider handling different server side / client side cases
// - runs wrapped component `getInitialProps` as expected
// - passes `store` to Component's `getInitialProps` so that it can dispatch actions
const withRefnux = (getInitialState, Component) => {
const Wrapper = props => {
2017-02-21 04:13:05 +00:00
var store = props.store
// if getInitialProps was executed on the server we get a store
// that's missing non-serializable functions.
2017-02-21 20:52:44 +00:00
// Because of this we need to recreate the store based on the
2017-02-21 04:13:05 +00:00
// state coming from the server.
if (!store.dispatch) {
store = getStore(props.store.state)
}
return (
<Provider
store={store}
app={() => <Component {...props.componentProps} />}
/>
)
2017-02-21 04:13:05 +00:00
}
Wrapper.getInitialProps = async function (context) {
const store = getStore(getInitialState())
var componentProps = {}
// honor wrapped component getInitialProps
if (Component.getInitialProps) {
componentProps = await Component.getInitialProps({ ...context, store })
}
return { store, componentProps }
}
return Wrapper
}
2017-02-21 20:52:44 +00:00
export default withRefnux