-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapolloClient.ts
60 lines (50 loc) · 1.67 KB
/
apolloClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import https from "https";
import { useMemo } from "react";
import {
ApolloClient,
createHttpLink,
InMemoryCache,
NormalizedCacheObject,
} from "@apollo/client";
import { isServer } from "../src/utils/isServer";
const isProd = process.env.NODE_ENV === "production";
let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;
const createApolloClient = () => {
return new ApolloClient({
ssrMode: isServer(),
link: createHttpLink({
fetchOptions: {
agent: new https.Agent({
rejectUnauthorized: isProd,
}),
},
uri: process.env.WORDPRESS_API_URL,
}),
cache: new InMemoryCache(),
});
};
export const initializeApollo = (initialState: any = 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) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract();
// Restore the cache using the data passed from getStaticProps/getServerSideProps
// combined with the existing cached data
_apolloClient.cache.restore({ ...existingCache, ...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;
};
export const useApollo = (initialState: any) => {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
};