Skip to content

Instantly share code, notes, and snippets.

@AlbionaHoti
Last active October 15, 2020 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbionaHoti/3d251625b1665f06c05cc7d6d643764b to your computer and use it in GitHub Desktop.
Save AlbionaHoti/3d251625b1665f06c05cc7d6d643764b to your computer and use it in GitHub Desktop.
e-commerce-starter
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,
// The CONTENT_DELIVERY_API_URL is comming from the `.env` file that you created on step 2 of the Prerequisites - Content Delivery API URL
// Server URL (must be absolute)
// credentials: 'same-origin',
// Additional fetch() options like `credentials` or `headers`
headers: {
authorization: process.env.CONTENT_DELIVERY_API_ACCESS_TOKEN,
// The CONTENT_DELIVERY_API_ACCESS_TOKEN is comming from the `.env` file that you created on step 3 of the Prerequisites - 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