Skip to content

Commit

Permalink
Make withApollo work with _app.js components
Browse files Browse the repository at this point in the history
  • Loading branch information
HaNdTriX committed Sep 19, 2019
1 parent 9b0c641 commit a4b02bd
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions examples/with-apollo/lib/apollo.js
@@ -1,4 +1,5 @@
import React, { useMemo } from 'react'
import App from 'next/app'
import Head from 'next/head'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloClient } from 'apollo-client'
Expand All @@ -17,6 +18,9 @@ let apolloClient = null
* @param {Boolean} [config.ssr=true]
*/
export function withApollo (PageComponent, { ssr = true } = {}) {
const isAppHoc =
PageComponent === App || PageComponent.prototype instanceof App

const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
const client = useMemo(
() => apolloClient || initApolloClient(apolloState),
Expand All @@ -29,15 +33,19 @@ export function withApollo (PageComponent, { ssr = true } = {}) {
)
}

if (process.env.NODE_ENV !== 'production') {
if (isAppHoc && ssr) {
console.warn(
'You are using the "withApollo" HOC on "_app.js" level. Please note that this disables project wide automatic static optimization. Better wrap your PageComponents directly.'
)
}
}

// Set the correct displayName in development
if (process.env.NODE_ENV !== 'production') {
const displayName =
PageComponent.displayName || PageComponent.name || 'Component'

if (displayName === 'App') {
console.warn('This withApollo HOC only works with PageComponents.')
}

WithApollo.displayName = `withApollo(${displayName})`
}

Expand Down Expand Up @@ -68,14 +76,14 @@ export function withApollo (PageComponent, { ssr = true } = {}) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient
}}
/>
)

// Since AppComponents and PageComponents have different context types
// we need to modify their props a little.
const props = isAppHoc
? { ...pageProps, apolloClient }
: { pageProps: { ...pageProps, apolloClient } }

await getDataFromTree(<AppTree {...props} />)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
Expand Down

0 comments on commit a4b02bd

Please sign in to comment.