with-redux-store.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* eslint-disable */
  2. import React from 'react';
  3. import initializeStore from './store';
  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 initializeStore(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__] = initializeStore(initialState);
  14. }
  15. return window[__NEXT_REDUX_STORE__];
  16. }
  17. export default App =>
  18. class AppWithRedux extends React.Component {
  19. static async getInitialProps(appContext) {
  20. // Get or Create the store with `undefined` as initialState
  21. // This allows you to set a custom default initialState
  22. const reduxStore = getOrCreateStore();
  23. // Provide the store to getInitialProps of pages
  24. appContext.ctx.reduxStore = reduxStore;
  25. let appProps = {};
  26. if (typeof App.getInitialProps === 'function') {
  27. appProps = await App.getInitialProps(appContext);
  28. }
  29. return {
  30. ...appProps,
  31. initialReduxState: reduxStore.getState(),
  32. };
  33. }
  34. constructor(props) {
  35. super(props);
  36. this.reduxStore = getOrCreateStore(props.initialReduxState);
  37. }
  38. render() {
  39. return <App {...this.props} reduxStore={this.reduxStore} />;
  40. }
  41. };