Skip to content

Instantly share code, notes, and snippets.

@AlbionaHoti
Last active October 11, 2020 18:08
Show Gist options
  • Save AlbionaHoti/54c3a3186606e4f21905d1a10b26e078 to your computer and use it in GitHub Desktop.
Save AlbionaHoti/54c3a3186606e4f21905d1a10b26e078 to your computer and use it in GitHub Desktop.
webiny-starter-e-commerce-nextjs-stripe
import { useMemo } from 'react'
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'
let apolloClient
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: process.env.CONTENT_DELIVERY_API_URL, // `.../cms/read/production`
// credentials: 'same-origin',
headers: {
authorization: process.env.CONTENT_DELIVERY_API_ACCESS_TOKEN,
},
}),
cache: new InMemoryCache(),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract()
// Restore the cache using the data passed from getStaticProps/getServerSideProps
// combined with the existing cached data
_apolloClient.cache.restore({ ...existingCache, ...initialState })
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment