forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql-client.js
40 lines (34 loc) · 1.35 KB
/
graphql-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
}