2018-12-10 15:50:35 +00:00
|
|
|
import React from 'react'
|
|
|
|
import initEnvironment from './createRelayEnvironment'
|
2019-01-31 09:38:20 +00:00
|
|
|
import { fetchQuery, ReactRelayContext } from 'react-relay'
|
2018-12-10 15:50:35 +00:00
|
|
|
|
|
|
|
export default (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) {
|
|
|
|
const variables = composedInitialProps.relayVariables || {}
|
|
|
|
// TODO: Consider RelayQueryResponseCache
|
|
|
|
// https://github.com/facebook/relay/issues/1687#issuecomment-302931855
|
|
|
|
queryProps = await fetchQuery(environment, options.query, variables)
|
2018-12-17 16:34:32 +00:00
|
|
|
queryRecords = environment
|
|
|
|
.getStore()
|
|
|
|
.getSource()
|
|
|
|
.toJSON()
|
2018-12-10 15:50:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...composedInitialProps,
|
|
|
|
...queryProps,
|
|
|
|
queryRecords
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
constructor (props) {
|
|
|
|
super(props)
|
|
|
|
this.environment = initEnvironment({
|
|
|
|
records: props.queryRecords
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
render () {
|
|
|
|
return (
|
2019-01-31 09:38:20 +00:00
|
|
|
<ReactRelayContext.Provider value={{ environment: this.environment, variables: {} }}>
|
2018-12-10 15:50:35 +00:00
|
|
|
<ComposedComponent {...this.props} />
|
2019-01-31 09:38:20 +00:00
|
|
|
</ReactRelayContext.Provider>
|
2018-12-10 15:50:35 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|