This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
withData.js
68 lines (60 loc) · 1.88 KB
/
withData.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
import { Component, PropTypes } from 'react';
import { ApolloProvider, getDataFromTree } from 'react-apollo';
import { loadGetInitialProps } from 'next/dist/lib/utils';
import 'isomorphic-fetch';
import getClientAndStore from '../data/clientAndStore';
function getInitialState(apolloClient, reduxStore) {
return {
...reduxStore.getState(),
apollo: {
data: apolloClient.getInitialState().data,
},
};
}
export default ComposedComponent => (
class WithData extends Component {
static propTypes = {
initialState: PropTypes.object.isRequired,
clientAndStoreProps: PropTypes.shape({
authToken: PropTypes.string,
}).isRequired,
};
static async getInitialProps(ctx) {
const subProps = await loadGetInitialProps(ComposedComponent, ctx);
const clientAndStoreProps = {
authToken: subProps.auth.token,
};
const { apolloClient, reduxStore } = getClientAndStore({}, clientAndStoreProps);
const props = {
url: { query: ctx.query, pathname: ctx.pathname },
...subProps,
};
if (!process.browser) {
await getDataFromTree((
<ApolloProvider client={apolloClient} store={reduxStore}>
<ComposedComponent {...props} />
</ApolloProvider>
));
}
return {
initialState: getInitialState(apolloClient, reduxStore),
clientAndStoreProps,
...props,
};
}
constructor(props) {
super(props);
const clientAndStore = getClientAndStore(this.props.initialState,
this.props.clientAndStoreProps);
this.apolloClient = clientAndStore.apolloClient;
this.reduxStore = clientAndStore.reduxStore;
}
render() {
return (
<ApolloProvider client={this.apolloClient} store={this.reduxStore}>
<ComposedComponent {...this.props} />
</ApolloProvider>
);
}
}
);