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
/
Copy pathwithData.js
72 lines (64 loc) · 1.99 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
69
70
71
72
import { Component, PropTypes } from 'react';
import { ApolloProvider, getDataFromTree } from 'react-apollo';
import 'isomorphic-fetch';
import getClientAndStore from '../data/clientAndStore';
import { getToken } from '../util/auth';
import getProps from '../util/initialProps';
export default ComposedComponent => (
class WithData extends Component {
static propTypes = {
url: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
initialState: PropTypes.object.isRequired,
headers: PropTypes.object.isRequired,
userToken: PropTypes.string,
};
static defaultProps = {
userToken: null,
};
static async getInitialProps(ctx) {
const headers = ctx.req ? ctx.req.headers : {};
const userToken = await getToken(ctx);
const { apolloClient, reduxStore } = getClientAndStore({}, headers, userToken);
const props = {
loggedIn: Boolean(userToken),
url: { query: ctx.query, pathname: ctx.pathname },
userToken,
...await getProps(ComposedComponent, ctx),
};
if (!process.browser) {
await getDataFromTree((
<ApolloProvider client={apolloClient} store={reduxStore}>
<ComposedComponent {...props} />
</ApolloProvider>
));
}
const state = reduxStore.getState();
return {
initialState: {
...state,
apollo: {
data: state.apollo.data,
},
},
headers,
...props,
};
}
constructor(props) {
super(props);
const clientAndStore = getClientAndStore(
this.props.initialState, this.props.headers, this.props.userToken);
this.apolloClient = clientAndStore.apolloClient;
this.reduxStore = clientAndStore.reduxStore;
}
render() {
return (
<ApolloProvider client={this.apolloClient} store={this.reduxStore}>
<ComposedComponent {...this.props} />
</ApolloProvider>
);
}
}
);