Last active
September 19, 2019 20:51
-
-
Save u840903/e0ed2566143d9ed02cae7c9a1c7bdcbb to your computer and use it in GitHub Desktop.
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 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