forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
withData.js
54 lines (47 loc) · 1.63 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
import React from 'react'
import initEnvironment from './createRelayEnvironment'
import { fetchQuery, ReactRelayContext } from 'react-relay'
export default function withData(ComposedComponent, options = {}) {
return class WithData extends React.Component {
static displayName = `WithData(${ComposedComponent.displayName})`
static async getInitialProps(ctx) {
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
let queryProps = {}
let queryRecords = {}
const environment = initEnvironment()
if (options.query) {
// Provide the `url` prop data in case a graphql query uses it
// const url = { query: ctx.query, pathname: ctx.pathname }
const variables = {}
// TODO: Consider RelayQueryResponseCache
// https://github.com/facebook/relay/issues/1687#issuecomment-302931855
queryProps = await fetchQuery(environment, options.query, variables)
queryRecords = environment.getStore().getSource().toJSON()
}
return {
...composedInitialProps,
...queryProps,
queryRecords,
}
}
constructor(props) {
super(props)
this.environment = initEnvironment({
records: props.queryRecords,
})
}
render() {
return (
<ReactRelayContext.Provider
value={{ environment: this.environment, variables: {} }}
>
<ComposedComponent {...this.props} />
</ReactRelayContext.Provider>
)
}
}
}