Use Redux and friends with Next.js.
WARNING: This library only supports Next.js v3. It does not work with later versions.
Differs from next-redux-wrapper in how state is transferred to the client. In next-redux-wrapper, the whole state is sent and used as the preloaded state in createStore()
. With Next Redux Replay only the actions responsible for the state are sent, which are then replayed on the client.
yarn install next-redux-replay
// some-page.js
import withRedux from "next-redux-replay";
const SomePage = () => <div />;
const makeStore = (actions, nextReduxReplayMiddleware, _isServer) => {
const store = createStore(
rootReducer,
applyMiddleware(nextReduxReplayMiddleware)
);
actions.forEach(action => store.dispatch(action));
return store;
};
const initStore = ({ store, isServer }) => {
store.dispatch(someAction());
const initialProps = {};
return Promise.resolve(initialProps);
}
export default withRedux(makeStore, initStore)(SomePage)
This function should create the store with the provided middleware then replay the recorded actions on the store. The middleware is responsible for collecting actions to be replayed on the client, so it should be placed in the middleware chain accordingly; i.e. after Redux Thunk.
Perform any setup and data fetching required here and return a promise. Whatever the promise resolves to will be merged with the wrapped page component's props
. This function serves the same purpose as getInitialProps()
, but receives the store
in addition to the normal `context' object.
Unlike next-redux-wrapper, this library does not connect your page components to the Redux store.