import { useMemo } from 'react' ; import { ApolloClient , InMemoryCache } from '@apollo/client' ; import { gqlBaseURL } from '@lib/constants' ; type ClientType = ReturnType < typeof createApolloClient > ; export let apolloClient ; function createApolloClient ( ) { return new ApolloClient ( { ssrMode : typeof window === 'undefined' , uri : gqlBaseURL , cache : new InMemoryCache ( ) , defaultOptions : { mutate : { fetchPolicy : 'no-cache' } } , } ) ; } export function initializeApollo ( initialState = { } ) { const _apolloClient = apolloClient ?? createApolloClient ( ) ; if ( initialState ) { const existingCache = _apolloClient . extract ( ) ; _apolloClient . cache . restore ( { ... existingCache , ... initialState } ) ; } if ( typeof window === 'undefined' ) return _apolloClient ; if ( ! apolloClient ) apolloClient = _apolloClient ; return _apolloClient ; } export function useApollo ( initialState = { } ) { const store = useMemo ( ( ) => initializeApollo ( initialState ) , [ initialState ] ) ; return store ; }