/
ApolloContext.tsx
43 lines (37 loc) · 1.35 KB
/
ApolloContext.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
import ApolloClient from 'apollo-client';
import React, { ReactElement, ReactNode, useContext } from 'react';
const ApolloContext = React.createContext<null | ApolloClient<any>>(null);
export interface ApolloProviderProps<TCacheShape> {
readonly children?: ReactNode;
readonly client: ApolloClient<TCacheShape>;
}
export function ApolloProvider<TCacheShape = any>({
client,
children,
}: ApolloProviderProps<TCacheShape>): ReactElement<
ApolloProviderProps<TCacheShape>
> {
return (
<ApolloContext.Provider value={client}>{children}</ApolloContext.Provider>
);
}
export function useApolloClient<TCache = object>(
overrideClient?: ApolloClient<TCache>
): ApolloClient<TCache> {
const client = useContext(ApolloContext);
// Ensures that the number of hooks called from one render to another remains
// constant, despite the Apollo client read from context being swapped for
// one passed directly as prop.
if (overrideClient) {
return overrideClient;
}
if (!client) {
// https://github.com/apollographql/react-apollo/blob/5cb63b3625ce5e4a3d3e4ba132eaec2a38ef5d90/src/component-utils.tsx#L19-L22
throw new Error(
'Could not find "client" in the context or passed in as a prop. ' +
'Wrap the root component in an <ApolloProvider>, or pass an ' +
'ApolloClient instance in via props.'
);
}
return client;
}