Unverified Commit b4ec9928 authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

[Examples] Move with-graphql-hooks to SSG (#13858)

Related to https://github.com/vercel/next.js/issues/11014

The setup is very similar to the one used for Apollo examples.

@Joezo I've removed the demo example that you added to the readme (https://github.com/vercel/next.js/pull/6482) as it will be outdated after this PR is merged.
parent 8dd3d2a8
...@@ -30,7 +30,7 @@ export function initializeApollo(initialState = null) { ...@@ -30,7 +30,7 @@ export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient() const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state // If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here // gets hydrated here
if (initialState) { if (initialState) {
_apolloClient.cache.restore(initialState) _apolloClient.cache.restore(initialState)
} }
......
...@@ -20,7 +20,7 @@ export function initializeApollo(initialState = null) { ...@@ -20,7 +20,7 @@ export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient() const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state // If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here // gets hydrated here
if (initialState) { if (initialState) {
_apolloClient.cache.restore(initialState) _apolloClient.cache.restore(initialState)
} }
......
...@@ -12,8 +12,6 @@ Deploy the example using [Vercel](https://vercel.com): ...@@ -12,8 +12,6 @@ Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/vercel/next.js/tree/canary/examples/with-graphql-hooks) [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/vercel/next.js/tree/canary/examples/with-graphql-hooks)
_Live Example: https://next-with-graphql-hooks.now.sh_
## How to use ## How to use
### Using `create-next-app` ### Using `create-next-app`
......
import Link from 'next/link' import Link from 'next/link'
import { withRouter } from 'next/router' import { useRouter } from 'next/router'
const Header = ({ router: { pathname } }) => ( export default function Header() {
const { pathname } = useRouter()
return (
<header> <header>
<Link href="/"> <Link href="/">
<a className={pathname === '/' ? 'is-active' : ''}>Home</a> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
...@@ -23,6 +26,5 @@ const Header = ({ router: { pathname } }) => ( ...@@ -23,6 +26,5 @@ const Header = ({ router: { pathname } }) => (
} }
`}</style> `}</style>
</header> </header>
) )
}
export default withRouter(Header)
import React, { Fragment, useState } from 'react' import { useState } from 'react'
import { useQuery } from 'graphql-hooks' import { useQuery } from 'graphql-hooks'
import ErrorMessage from './error-message' import ErrorMessage from './error-message'
import PostUpvoter from './post-upvoter' import PostUpvoter from './post-upvoter'
...@@ -19,9 +19,7 @@ export const allPostsQuery = ` ...@@ -19,9 +19,7 @@ export const allPostsQuery = `
} }
` `
export default function PostList() { export const allPostsQueryOptions = (skip = 0) => ({
const [skip, setSkip] = useState(0)
const { loading, error, data, refetch } = useQuery(allPostsQuery, {
variables: { skip, first: 10 }, variables: { skip, first: 10 },
updateData: (prevResult, result) => ({ updateData: (prevResult, result) => ({
...result, ...result,
...@@ -29,7 +27,14 @@ export default function PostList() { ...@@ -29,7 +27,14 @@ export default function PostList() {
? [...prevResult.allPosts, ...result.allPosts] ? [...prevResult.allPosts, ...result.allPosts]
: result.allPosts, : result.allPosts,
}), }),
}) })
export default function PostList() {
const [skip, setSkip] = useState(0)
const { loading, error, data, refetch } = useQuery(
allPostsQuery,
allPostsQueryOptions(skip)
)
if (error) return <ErrorMessage message="Error loading posts." /> if (error) return <ErrorMessage message="Error loading posts." />
if (!data) return <div>Loading</div> if (!data) return <div>Loading</div>
...@@ -38,7 +43,7 @@ export default function PostList() { ...@@ -38,7 +43,7 @@ export default function PostList() {
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
<Fragment> <>
<Submit <Submit
onSubmission={() => { onSubmission={() => {
refetch({ variables: { skip: 0, first: allPosts.length } }) refetch({ variables: { skip: 0, first: allPosts.length } })
...@@ -109,6 +114,6 @@ export default function PostList() { ...@@ -109,6 +114,6 @@ export default function PostList() {
} }
`}</style> `}</style>
</section> </section>
</Fragment> </>
) )
} }
import { useMemo } from 'react'
import { GraphQLClient } from 'graphql-hooks'
import memCache from 'graphql-hooks-memcache'
let graphQLClient
function createClient(initialState) {
return new GraphQLClient({
ssrMode: typeof window === 'undefined',
url: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
cache: memCache({ initialState }),
})
}
export function initializeGraphQL(initialState = null) {
const _graphQLClient = graphQLClient ?? createClient(initialState)
// After navigating to a page with an initial GraphQL state, create a new cache with the
// current state merged with the incoming state and set it to the GraphQL client.
// This is necessary because the initial state of `memCache` can only be set once
if (initialState && graphQLClient) {
graphQLClient.cache = memCache({
initialState: Object.assign(
graphQLClient.cache.getInitialState(),
initialState
),
})
}
// For SSG and SSR always create a new GraphQL Client
if (typeof window === 'undefined') return _graphQLClient
// Create the GraphQL Client once in the client
if (!graphQLClient) graphQLClient = _graphQLClient
return _graphQLClient
}
export function useGraphQLClient(initialState) {
const store = useMemo(() => initializeGraphQL(initialState), [initialState])
return store
}
const defaultOpts = { useCache: true }
/**
* Returns the result of a GraphQL query. It also adds the result to the
* cache of the GraphQL client for better initial data population in pages.
*
* Note: This helper tries to imitate what the query hooks of `graphql-hooks`
* do internally to make sure we generate the same cache key
*/
export default async function graphQLRequest(client, query, options) {
const opts = { ...defaultOpts, ...options }
const operation = {
query,
variables: opts.variables,
operationName: opts.operationName,
persisted: opts.persisted,
}
if (opts.persisted || (client.useGETForQueries && !opts.isMutation)) {
opts.fetchOptionsOverrides = {
...opts.fetchOptionsOverrides,
method: 'GET',
}
}
const cacheKey = client.getCacheKey(operation, opts)
const cacheValue = await client.request(operation, opts)
client.saveCache(cacheKey, cacheValue)
return cacheValue
}
import { GraphQLClient } from 'graphql-hooks'
import memCache from 'graphql-hooks-memcache'
let graphQLClient = null
function create(initialState = {}) {
return new GraphQLClient({
ssrMode: typeof window === 'undefined',
url: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn',
cache: memCache({ initialState }),
})
}
export default function initGraphQL(initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return create(initialState)
}
// Reuse client on the client-side
if (!graphQLClient) {
graphQLClient = create(initialState)
}
return graphQLClient
}
import React from 'react'
import initGraphQL from './init-graphql'
import Head from 'next/head'
import { getInitialState } from 'graphql-hooks-ssr'
export default function withGraphqlClient(App) {
return class GraphQLHooks extends React.Component {
static displayName = 'GraphQLHooks(App)'
static async getInitialProps(ctx) {
const { AppTree } = ctx
let appProps = {}
if (App.getInitialProps) {
appProps = await App.getInitialProps(ctx)
}
// Run all GraphQL queries in the component tree
// and extract the resulting data
let graphQLState = {}
if (typeof window === 'undefined') {
const graphQLClient = initGraphQL()
try {
// Run all GraphQL queries
graphQLState = await getInitialState({
App: <AppTree {...appProps} graphQLClient={graphQLClient} />,
client: graphQLClient,
})
} catch (error) {
// Prevent GraphQL hooks client errors from crashing SSR.
// Handle them in components via the state.error prop:
// https://github.com/nearform/graphql-hooks#usequery
console.error('Error while running `getInitialState`', error)
}
// getInitialState does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
}
return {
...appProps,
graphQLState,
}
}
constructor(props) {
super(props)
if (props.graphQLClient) {
// During SSR the GraphQL client is provided as a prop
this.graphQLClient = props.graphQLClient
} else {
this.graphQLClient = initGraphQL(props.graphQLState)
}
}
render() {
return <App {...this.props} graphQLClient={this.graphQLClient} />
}
}
}
{ {
"name": "with-graphql-hooks", "name": "with-graphql-hooks",
"version": "1.0.0", "version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"start": "next start" "start": "next start"
}, },
"author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"graphql-hooks": "^4.4.4", "graphql-hooks": "^4.4.4",
"graphql-hooks-memcache": "^1.3.2", "graphql-hooks-memcache": "^1.3.2",
"graphql-hooks-ssr": "^1.1.5",
"next": "latest", "next": "latest",
"prop-types": "^15.7.2", "prop-types": "^15.7.2",
"react": "^16.8.2", "react": "^16.8.2",
"react-dom": "^16.8.2" "react-dom": "^16.8.2"
},
"browser": {
"graphql-hooks-ssr": false
} }
} }
import App from 'next/app'
import withGraphQLClient from '../lib/with-graphql-client'
import { ClientContext } from 'graphql-hooks' import { ClientContext } from 'graphql-hooks'
import { useGraphQLClient } from '../lib/graphql-client'
export default function App({ Component, pageProps }) {
const graphQLClient = useGraphQLClient(pageProps.initialGraphQLState)
class MyApp extends App {
render() {
const { Component, pageProps, graphQLClient } = this.props
return ( return (
<ClientContext.Provider value={graphQLClient}> <ClientContext.Provider value={graphQLClient}>
<Component {...pageProps} /> <Component {...pageProps} />
</ClientContext.Provider> </ClientContext.Provider>
) )
}
} }
export default withGraphQLClient(MyApp)
import { initializeGraphQL } from '../lib/graphql-client'
import graphQLRequest from '../lib/graphql-request'
import App from '../components/app' import App from '../components/app'
import Header from '../components/header' import Header from '../components/header'
import PostList from '../components/post-list' import PostList, {
allPostsQuery,
allPostsQueryOptions,
} from '../components/post-list'
export default function Home() { export default function Home() {
return ( return (
...@@ -10,3 +15,16 @@ export default function Home() { ...@@ -10,3 +15,16 @@ export default function Home() {
</App> </App>
) )
} }
export async function getStaticProps() {
const client = initializeGraphQL()
await graphQLRequest(client, allPostsQuery, allPostsQueryOptions())
return {
props: {
initialGraphQLState: client.cache.getInitialState(),
},
unstable_revalidate: 1,
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment