Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
1import * as React from 'react';
2import type { Client } from '@urql/core';
3
4const OBJ = {};
5
6/** `urql`'s React Context.
7 *
8 * @remarks
9 * The React Context that `urql`’s {@link Client} will be provided with.
10 * You may use the reexported {@link Provider} to provide a `Client` as well.
11 */
12export const Context: import('react').Context<Client | object> =
13 React.createContext(OBJ);
14
15/** Provider for `urql`'s {@link Client} to GraphQL hooks.
16 *
17 * @remarks
18 * `Provider` accepts a {@link Client} and provides it to all GraphQL hooks,
19 * and {@link useClient}.
20 *
21 * You should make sure to create a {@link Client} and provide it with the
22 * `Provider` to parts of your component tree that use GraphQL hooks.
23 *
24 * @example
25 * ```tsx
26 * import { Provider } from 'urql';
27 * // All of `@urql/core` is also re-exported by `urql`:
28 * import { Client, cacheExchange, fetchExchange } from '@urql/core';
29 *
30 * const client = new Client({
31 * url: 'https://API',
32 * exchanges: [cacheExchange, fetchExchange],
33 * });
34 *
35 * const App = () => (
36 * <Provider value={client}>
37 * <Component />
38 * </Provider>
39 * );
40 * ```
41 */
42export const Provider: React.Provider<Client | object> = Context.Provider;
43
44/** React Consumer component, providing the {@link Client} provided on a parent component.
45 * @remarks
46 * This is an alias for {@link Context.Consumer}.
47 */
48export const Consumer: React.Consumer<Client | object> = Context.Consumer;
49
50Context.displayName = 'UrqlContext';
51
52/** Hook returning a {@link Client} from {@link Context}.
53 *
54 * @remarks
55 * `useClient` is a convenience hook, which accesses `urql`'s {@link Context}
56 * and returns the {@link Client} defined on it.
57 *
58 * This will be the {@link Client} you passed to a {@link Provider}
59 * you wrapped your elements containing this hook with.
60 *
61 * @throws
62 * In development, if the component you call `useClient()` in is
63 * not wrapped in a {@link Provider}, an error is thrown.
64 */
65export const useClient = (): Client => {
66 const client = React.useContext(Context);
67
68 if (client === OBJ && process.env.NODE_ENV !== 'production') {
69 const error =
70 "No client has been specified using urql's Provider. please create a client and add a Provider.";
71
72 console.error(error);
73 throw new Error(error);
74 }
75
76 return client as Client;
77};