Skip to content

Instantly share code, notes, and snippets.

@stephen-dahl
Last active July 8, 2019 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephen-dahl/a4deb18f54d5138227171064f9cb3e4f to your computer and use it in GitHub Desktop.
Save stephen-dahl/a4deb18f54d5138227171064f9cb3e4f to your computer and use it in GitHub Desktop.
nextjs redux store with initial state from SSR
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);
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