2023-03-10 14:39:31 +03:00

31 lines
940 B
JavaScript

import { link } from '@/config/apollo';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { isServer } from 'tools/common';
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
let apolloClient;
function createApolloClient() {
return new ApolloClient({
cache: new InMemoryCache(),
link,
ssrMode: isServer(),
});
}
export default 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);
}
// 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;
}