2018-05-07 13:02:56 +00:00
|
|
|
import initApollo from './init-apollo'
|
|
|
|
import Head from 'next/head'
|
|
|
|
import { getDataFromTree } from 'react-apollo'
|
|
|
|
|
|
|
|
export default (App) => {
|
|
|
|
return class Apollo extends React.Component {
|
|
|
|
static displayName = 'withApollo(App)'
|
|
|
|
static async getInitialProps (ctx) {
|
|
|
|
const { Component, router } = ctx
|
|
|
|
|
|
|
|
let appProps = {}
|
|
|
|
if (App.getInitialProps) {
|
|
|
|
appProps = await App.getInitialProps(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run all GraphQL queries in the component tree
|
|
|
|
// and extract the resulting data
|
|
|
|
const apollo = initApollo()
|
|
|
|
if (!process.browser) {
|
2018-07-05 18:49:23 +00:00
|
|
|
try {
|
|
|
|
// Run all GraphQL queries
|
|
|
|
await getDataFromTree(
|
|
|
|
<App
|
|
|
|
{...appProps}
|
|
|
|
Component={Component}
|
|
|
|
router={router}
|
|
|
|
apolloClient={apollo}
|
|
|
|
/>
|
|
|
|
)
|
|
|
|
} catch (error) {
|
|
|
|
// Prevent Apollo Client GraphQL errors from crashing SSR.
|
|
|
|
// Handle them in components via the data.error prop:
|
2018-08-09 21:00:08 +00:00
|
|
|
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
|
2018-07-05 18:49:23 +00:00
|
|
|
console.error('Error while running `getDataFromTree`', error)
|
|
|
|
}
|
|
|
|
|
2018-05-07 13:02:56 +00:00
|
|
|
// getDataFromTree does not call componentWillUnmount
|
|
|
|
// head side effect therefore need to be cleared manually
|
|
|
|
Head.rewind()
|
2018-07-05 18:49:23 +00:00
|
|
|
}
|
2018-05-07 13:02:56 +00:00
|
|
|
|
2018-07-12 16:59:28 +00:00
|
|
|
// Extract query data from the Apollo store
|
|
|
|
const apolloState = apollo.cache.extract()
|
|
|
|
|
2018-05-07 13:02:56 +00:00
|
|
|
return {
|
|
|
|
...appProps,
|
|
|
|
apolloState
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
constructor (props) {
|
|
|
|
super(props)
|
2018-07-12 16:59:28 +00:00
|
|
|
this.apolloClient = initApollo(props.apolloState)
|
2018-05-07 13:02:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
render () {
|
|
|
|
return <App {...this.props} apolloClient={this.apolloClient} />
|
|
|
|
}
|
|
|
|
}
|
2018-05-29 17:33:21 +00:00
|
|
|
}
|