Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix getInitialProps issue in with-apollo example #8620

Merged
merged 8 commits into from
Sep 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/with-apollo/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ const Header = ({ router: { pathname } }) => (
<Link href='/'>
<a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link>
<Link href='/client-only'>
<a className={pathname === '/client-only' ? 'is-active' : ''}>
Client-Only
</a>
</Link>
<Link href='/about'>
<a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link>
Expand Down
17 changes: 17 additions & 0 deletions examples/with-apollo/components/InfoBox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const InfoBox = ({ children }) => (
<div className='info'>
<style jsx>{`
.info {
margin-top: 20px;
margin-bottom: 20px;
padding-top: 20px;
padding-bottom: 20px;
border-top: 1px solid #ececec;
border-bottom: 1px solid #ececec;
}
`}</style>
{children}
</div>
)

export default InfoBox
2 changes: 1 addition & 1 deletion examples/with-apollo/components/PostList.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useQuery } from '@apollo/react-hooks'
import { NetworkStatus } from 'apollo-boost'
import { NetworkStatus } from 'apollo-client'
import gql from 'graphql-tag'
import ErrorMessage from './ErrorMessage'
import PostUpvoter from './PostUpvoter'
Expand Down
97 changes: 53 additions & 44 deletions examples/with-apollo/lib/apollo.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useMemo } from 'react'
import Head from 'next/head'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloClient, InMemoryCache, HttpLink } from 'apollo-boost'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import fetch from 'isomorphic-unfetch'

let apolloClient = null
Expand Down Expand Up @@ -39,50 +41,60 @@ export function withApollo (PageComponent, { ssr = true } = {}) {
WithApollo.displayName = `withApollo(${displayName})`
}

// Allow Next.js to remove getInitialProps from the browser build
if (typeof window === 'undefined') {
if (ssr) {
WithApollo.getInitialProps = async ctx => {
const { AppTree } = ctx
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
const { AppTree } = ctx

let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
}
// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
const apolloClient = (ctx.apolloClient = initApolloClient())

// Run wrapped getInitialProps methods
let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
}

// Run all GraphQL queries in the component tree
// and extract the resulting data
const apolloClient = initApolloClient()

try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient
}}
/>
)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error)
// Only on the server:
if (typeof window === 'undefined') {
// When redirecting, the response is finished.
// No point in continuing to render
if (ctx.res && ctx.res.finished) {
return pageProps
}

// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
// Only if ssr is enabled
if (ssr) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient
}}
/>
)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error)
}

// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
}
}

// Extract query data from the Apollo store
const apolloState = apolloClient.cache.extract()
// Extract query data from the Apollo store
const apolloState = apolloClient.cache.extract()

return {
...pageProps,
apolloState
}
return {
...pageProps,
apolloState
}
}
}
Expand Down Expand Up @@ -116,15 +128,12 @@ function initApolloClient (initialState) {
*/
function createApolloClient (initialState = {}) {
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
const isBrowser = typeof window !== 'undefined'
return new ApolloClient({
connectToDevTools: isBrowser,
ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
// Use fetch() polyfill on the server
fetch: !isBrowser && fetch
fetch
}),
cache: new InMemoryCache().restore(initialState)
})
Expand Down
6 changes: 4 additions & 2 deletions examples/with-apollo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
"dependencies": {
"@apollo/react-hooks": "3.0.0",
"@apollo/react-ssr": "3.0.0",
"apollo-boost": "0.4.4",
"apollo-cache-inmemory": "1.6.3",
"apollo-client": "2.6.4",
"apollo-link-http": "1.5.15",
"graphql": "^14.0.2",
"graphql-tag": "2.10.1",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"prop-types": "^15.6.2",
"react": "^16.7.0",
"react-dom": "^16.7.0"
},
"author": "",
"license": "ISC"
}
31 changes: 31 additions & 0 deletions examples/with-apollo/pages/client-only.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import App from '../components/App'
import InfoBox from '../components/InfoBox'
import Header from '../components/Header'
import Submit from '../components/Submit'
import PostList from '../components/PostList'
import { withApollo } from '../lib/apollo'

const ClientOnlyPage = props => (
<App>
<Header />
<InfoBox>
ℹ️ This example shows how to disable apollos query fetching on the server.
If you <a href='/client-only'>reload</a> this page, you will see a loader
since Apollo didn't fetch any data on the server. This allows{' '}
<a
href='https://nextjs.org/blog/next-9#automatic-static-optimization'
target='_blank'
>
automatic static optimization
</a>
.
</InfoBox>
<Submit />
<PostList />
</App>
)

export default withApollo(ClientOnlyPage, {
// Disable apollo ssr fetching in favour of automatic static optimization
ssr: false
})
13 changes: 13 additions & 0 deletions examples/with-apollo/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import App from '../components/App'
import InfoBox from '../components/InfoBox'
import Header from '../components/Header'
import Submit from '../components/Submit'
import PostList from '../components/PostList'
Expand All @@ -7,6 +8,18 @@ import { withApollo } from '../lib/apollo'
const IndexPage = props => (
<App>
<Header />
<InfoBox>
ℹ️ This example shows how to fetch all initial apollo queries on the
server. If you <a href='/'>reload</a> this page you won't see a loader
since Apollo fetched all needed data on the server. This prevents{' '}
<a
href='https://nextjs.org/blog/next-9#automatic-static-optimization'
target='_blank'
>
automatic static optimization
</a>{' '}
in favour of full Server-Side-Rendering.
</InfoBox>
<Submit />
<PostList />
</App>
Expand Down