Created
December 14, 2020 21:38
-
-
Save taleschaves/cb2c88c28db008133cdb60c740c1b112 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, InMemoryCache, split, HttpLink } from '@apollo/client'; | |
let apolloClient; | |
const BFF = new HttpLink({ | |
uri: '/graphql', | |
headers: { 'schema-variant': 'integration' } | |
}); | |
const ContentPerf = new HttpLink({ | |
uri: '/contentperf' | |
}); | |
/* | |
How do we tell a component which GraphQL API to query? By using the context of the query. Here is an example: | |
*/ | |
function createApolloClient() { | |
return new ApolloClient({ | |
ssrMode: false, | |
link: split((operation) => operation.getContext().clientName === 'ContentPerf', ContentPerf, BFF), | |
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) { | |
_apolloClient.cache.restore(initialState); | |
} | |
// 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