Last active
July 8, 2019 20:02
-
-
Save stephen-dahl/a4deb18f54d5138227171064f9cb3e4f to your computer and use it in GitHub Desktop.
nextjs redux store with initial state from SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { connect } from 'react-redux'; | |
import withRedux from './withRedux'; | |
const Index = props => ( | |
<pre> | |
<h1>State</h1> | |
{JSON.stringify(props, null, 2)} | |
</pre> | |
); | |
export default withRedux(reducer, Index); | |
//or if you need to use state in your root component | |
const ConnectedIndex = connect(state => state)(Index); | |
export default withRedux(reducer, ConnectedIndex); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createStore, compose, applyMiddleware } from 'redux'; | |
import { Provider } from 'react-redux'; | |
import thunk from 'redux-thunk'; | |
export function makeStore(reducer, initialState) { | |
return createStore(reducer, initialState); | |
} | |
const withRedux = (reducer, Page) => { | |
const WithRedux = props => { | |
const store = props.store.getState | |
? props.store | |
: makeStore(reducer, props.state); | |
return ( | |
<Provider store={store}> | |
<Page /> | |
</Provider> | |
); | |
}; | |
WithRedux.getInitialProps = async args => { | |
const store = (args.store = makeStore(reducer)); | |
const state = store.getState(); | |
const pageProps = Page.getInitialProps | |
? await Page.getInitialProps(args) | |
: {}; | |
return { store, state, ...pageProps }; | |
}; | |
return WithRedux; | |
}; | |
export default withRedux; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment