import React , { useMemo } from 'react' ; import { NextPage } from 'next' ; import { ApolloProvider , ApolloClient , InMemoryCache , NormalizedCacheObject , HttpLink , } from '@apollo/client' ; import { apiURL } from '../utils/api-url' ; const isServer = typeof window === 'undefined' ; let apolloClient ; const apolloClientCache = new InMemoryCache ( ) ; function createApolloClient ( ) { return new ApolloClient ( { ssrMode : isServer , connectToDevTools : ! isServer , link : new HttpLink ( { uri : `${ apiURL }/graphql` } ) , cache : apolloClientCache , queryDeduplication : true , } ) ; } export function initializeApollo ( initialState ) { const _apolloClient = apolloClient ?? createApolloClient ( ) ; if ( initialState ) { _apolloClient . cache . restore ( initialState ) ; } if ( typeof window === 'undefined' ) return _apolloClient ; if ( ! apolloClient ) apolloClient = _apolloClient ; return _apolloClient ; } export function withApollo ( Component ) { return ( props ) => { const pageApolloClient = useMemo ( ( ) => initializeApollo ( props . initialApolloState ) , [ props . initialApolloState ] ) ; return ( < ApolloProvider client = { pageApolloClient } > < Component { ... props } / > < /ApolloProvider>); } ; }