2017-03-12 07:33:01 +00:00
|
|
|
import React from 'react'
|
2017-05-10 22:23:11 +00:00
|
|
|
import PropTypes from 'prop-types'
|
2017-03-12 07:33:01 +00:00
|
|
|
import { ApolloProvider, getDataFromTree } from 'react-apollo'
|
2017-05-10 22:23:11 +00:00
|
|
|
import initApollo from './initApollo'
|
|
|
|
|
|
|
|
export default ComposedComponent => {
|
|
|
|
return class WithData extends React.Component {
|
|
|
|
static displayName = `WithData(${ComposedComponent.displayName})`
|
|
|
|
static propTypes = {
|
|
|
|
serverState: PropTypes.object.isRequired
|
|
|
|
}
|
2017-01-22 12:27:06 +00:00
|
|
|
|
|
|
|
static async getInitialProps (ctx) {
|
2017-05-10 22:23:11 +00:00
|
|
|
let serverState = {}
|
2017-01-22 12:27:06 +00:00
|
|
|
|
2017-05-10 22:23:11 +00:00
|
|
|
// Evaluate the composed component's getInitialProps()
|
|
|
|
let composedInitialProps = {}
|
|
|
|
if (ComposedComponent.getInitialProps) {
|
|
|
|
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
|
2017-01-26 01:10:21 +00:00
|
|
|
}
|
|
|
|
|
2017-05-10 22:23:11 +00:00
|
|
|
// Run all graphql queries in the component tree
|
|
|
|
// and extract the resulting data
|
2017-01-22 12:27:06 +00:00
|
|
|
if (!process.browser) {
|
2017-05-10 22:23:11 +00:00
|
|
|
const apollo = initApollo()
|
|
|
|
// Provide the `url` prop data in case a graphql query uses it
|
|
|
|
const url = {query: ctx.query, pathname: ctx.pathname}
|
|
|
|
|
|
|
|
// Run all graphql queries
|
2017-01-22 12:27:06 +00:00
|
|
|
const app = (
|
2017-05-10 22:23:11 +00:00
|
|
|
<ApolloProvider client={apollo}>
|
|
|
|
<ComposedComponent url={url} {...composedInitialProps} />
|
2017-01-22 12:27:06 +00:00
|
|
|
</ApolloProvider>
|
|
|
|
)
|
|
|
|
await getDataFromTree(app)
|
2017-05-10 22:23:11 +00:00
|
|
|
|
|
|
|
// Extract query data from the Apollo's store
|
|
|
|
const state = apollo.getInitialState()
|
|
|
|
|
|
|
|
serverState = {
|
|
|
|
apollo: { // Make sure to only include Apollo's data state
|
|
|
|
data: state.data
|
|
|
|
}
|
|
|
|
}
|
2017-01-22 12:27:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2017-05-10 22:23:11 +00:00
|
|
|
serverState,
|
|
|
|
...composedInitialProps
|
2017-01-22 12:27:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
constructor (props) {
|
|
|
|
super(props)
|
2017-05-10 22:23:11 +00:00
|
|
|
this.apollo = initApollo(this.props.serverState)
|
2017-01-22 12:27:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
render () {
|
|
|
|
return (
|
2017-05-10 22:23:11 +00:00
|
|
|
<ApolloProvider client={this.apollo}>
|
|
|
|
<ComposedComponent {...this.props} />
|
2017-01-22 12:27:06 +00:00
|
|
|
</ApolloProvider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2017-05-10 22:23:11 +00:00
|
|
|
}
|