Last active
October 15, 2020 00:05
-
-
Save AlbionaHoti/3d251625b1665f06c05cc7d6d643764b to your computer and use it in GitHub Desktop.
e-commerce-starter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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