-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwithReduxStore.js
54 lines (42 loc) · 1.52 KB
/
withReduxStore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* eslint-disable no-underscore-dangle, @typescript-eslint/no-explicit-any */
import React from "react";
import initializeStore from "./src/store";
import { isServer } from "./isServer";
const __NEXT_REDUX_STORE__ = "__NEXT_REDUX_STORE__";
function getOrCreateStore(initialState) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return initializeStore(initialState);
}
// Create store if unavailable on the client and set it on the window object
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = initializeStore(initialState);
}
return window[__NEXT_REDUX_STORE__];
}
export const withReduxStore = App =>
class AppWithRedux extends React.Component {
reduxStore;
static async getInitialProps(appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const reduxStore = getOrCreateStore();
// Provide the store to getInitialProps of pages
appContext.ctx.store = reduxStore;
let appProps = {};
if (typeof App.getInitialProps === "function") {
appProps = await App.getInitialProps.call(App, appContext);
}
return {
...appProps,
initialReduxState: reduxStore.getState()
};
}
constructor(props) {
super(props);
this.reduxStore = getOrCreateStore(props.initialReduxState);
}
render() {
return <App {...this.props} reduxStore={this.reduxStore} />;
}
};