Skip to content

Instantly share code, notes, and snippets.

@u840903
Last active September 19, 2019 20:51
Show Gist options
  • Save u840903/e0ed2566143d9ed02cae7c9a1c7bdcbb to your computer and use it in GitHub Desktop.
Save u840903/e0ed2566143d9ed02cae7c9a1c7bdcbb to your computer and use it in GitHub Desktop.
import React from "react";
import { END } from "redux-saga";
const STORE_KEY = "__NEXT_REDUX_STORE__";
export const withReduxSaga = makeStore => {
const isServer = typeof window === "undefined";
const initStore = ({ initialState, ctx }) => {
const createStore = () =>
makeStore(initialState, {
...ctx,
isServer
});
if (isServer) {
return createStore();
}
if (!window.hasOwnProperty(STORE_KEY)) {
window[STORE_KEY] = createStore();
}
return window[STORE_KEY];
};
return App => {
const WrappedApp = foo => {
const { initialState } = foo;
const store = initStore({ initialState });
const { initialProps, ...props } = foo;
return <App {...props} {...initialProps} store={store} />;
};
WrappedApp.getInitialProps = async props => {
const { ctx } = props;
const store = initStore({ ctx });
ctx.store = store;
ctx.isServer = isServer;
const initialProps = App.getInitialProps
? await App.getInitialProps.call(App, props)
: {};
if (isServer) {
store.dispatch(END);
await store.sagaTask.toPromise();
}
return {
isServer,
initialState: store.getState(),
initialProps
};
};
return WrappedApp;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment