2024-05-21 13:51:57 +03:00

31 lines
974 B
JavaScript

import { createLink } from './link';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { isServer } from 'tools/common';
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
let apolloClient;
function createApolloClient(headers) {
return new ApolloClient({
cache: new InMemoryCache(),
link: createLink(headers),
ssrMode: isServer(),
});
}
export default function initializeApollo(initialState, headers) {
const _apolloClient = apolloClient ?? createApolloClient(headers);
// 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);
}
// For SSG and SSR always create a new Apollo Client
if (isServer()) return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}