-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApolloClientProvider.tsx
52 lines (45 loc) · 1.48 KB
/
ApolloClientProvider.tsx
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
import { ReactNode, useEffect, useMemo, useRef } from "react";
import {
ApolloClient,
ApolloProvider,
createHttpLink,
InMemoryCache,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import _ from "lodash";
import { useAuthAccessTokenContext } from "./useAuthAccessTokenContext";
export const ApolloClientProvider = ({ children }: { children: ReactNode }) => {
const { accessToken } = useAuthAccessTokenContext();
const accessTokenRef = useRef<string | undefined>();
useEffect(() => {
accessTokenRef.current = accessToken;
}, [accessToken]);
const apolloClient = useMemo(() => {
const httpLink = createHttpLink({
uri: (operation) => {
// encodeURIComponent: a standard JavaScript function that encodes
// special characters in a URL, preventing a possible injection attack vector
return `/api/graphql?operationName=${encodeURIComponent(
operation.operationName,
)}`;
},
});
const authLink = setContext((__, { headers }) => {
const token = accessTokenRef.current;
return {
headers: _.omitBy(
{
...headers,
authorization: token ? `Bearer ${token}` : undefined,
},
_.isNil,
),
};
});
return new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
}, [accessTokenRef]);
return <ApolloProvider client={apolloClient}>{children}</ApolloProvider>;
};