with-redux-store.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import React from 'react';
  2. import configureStore from './store.js';
  3. import { readState, saveState } from './persisted.store.cookies.js';
  4. const isServer = typeof window === 'undefined';
  5. const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__';
  6. function getOrCreateStore(initialState) {
  7. // Always make a new store if server, otherwise state is shared between requests
  8. if (isServer) {
  9. return configureStore(initialState);
  10. }
  11. // Create store if unavailable on the client and set it on the window object
  12. if (!window[__NEXT_REDUX_STORE__]) {
  13. window[__NEXT_REDUX_STORE__] = configureStore(initialState);
  14. }
  15. return window[__NEXT_REDUX_STORE__];
  16. }
  17. const AppFn = App => {
  18. return class AppWithRedux extends React.Component {
  19. static async getInitialProps(appContext) {
  20. let initialState = appContext.ctx.req
  21. ? readState(appContext.ctx.req.headers.cookie)
  22. : {};
  23. // Get or Create the store with `undefined` as initialState
  24. // This allows you to set a custom default initialState
  25. const reduxStore = getOrCreateStore(initialState);
  26. // Provide the store to getInitialProps of pages
  27. appContext.ctx.reduxStore = reduxStore;
  28. let appProps = {};
  29. if (typeof App.getInitialProps === 'function') {
  30. appProps = await App.getInitialProps(appContext);
  31. }
  32. return {
  33. ...appProps,
  34. initialReduxState: reduxStore.getState()
  35. };
  36. }
  37. constructor(props) {
  38. super(props);
  39. this.reduxStore = getOrCreateStore(props.initialReduxState);
  40. }
  41. render() {
  42. return <App {...this.props} reduxStore={this.reduxStore} />;
  43. }
  44. };
  45. };
  46. export default AppFn;