-
Notifications
You must be signed in to change notification settings - Fork 0
/
_app.js
72 lines (57 loc) · 1.86 KB
/
_app.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useMemo } from 'react';
import { Provider } from 'react-redux';
import App, { AppContext } from 'next/app';
import handleServerActions from '@wishy-gift/noscript/dist/utils/handleServerActions';
import { addActionCreators } from '@wishy-gift/noscript/dist/utils/actionCreators';
import getStore from './getStore';
import { fetchBooks } from './gutenberg/gutenbergSlice';
import { incrementBySurprise } from './counter/counterSlice';
// these are action creators, and needs to be passed in to `addActionCreators`
// so that the correct action creator can be run server side
addActionCreators({ fetchBooks, incrementBySurprise });
function MyApp({ Component, pageProps, preloadedState, isServer }) {
const reduxStore = useMemo(
() => getStore(preloadedState, isServer),
[isServer, preloadedState]
);
return (
<Provider store={reduxStore}>
<Component {...pageProps} />
</Provider>
);
}
/**
* @type {Function}
* @param {AppContext} appContext
*/
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
const req = appContext.ctx.req;
const isServer = Boolean(req);
const isPost = req?.method.toLowerCase() === 'post';
let preloadedState;
// One of the basic assumptions we make, is that the only reason why someone would do a POST-request to a view route
// is because they've disabled JS, and an action has been dispatched
// this way we know when to update the client state for our users server-side, and re-render the page
if (isPost) {
const rawBody = req.read().toString();
const result = await handleServerActions({
rawBody,
getReduxStore: (state) => {
return getStore(state, isServer);
},
});
preloadedState = result.state;
}
const pageProps = {
isPost,
...appProps.pageProps,
};
return {
...appProps,
pageProps,
preloadedState,
isServer,
};
};
export default MyApp;