UNPKG

2.22 kBJavaScriptView Raw
1'use strict';
2
3const { useRef } = require('react');
4const { jsx } = require('react/jsx-runtime');
5const Cache = require('./Cache');
6const CacheContext = require('./CacheContext');
7const HydrationTimeStampContext = require('./HydrationTimeStampContext');
8const Loading = require('./Loading');
9const LoadingContext = require('./LoadingContext');
10
11/**
12 * A React component to provide all the React context required to enable the
13 * entire `graphql-react` API:
14 *
15 * - [Hydration time stamp context]{@link HydrationTimeStampContext}
16 * - [Cache context]{@link CacheContext}
17 * - [Loading context]{@link LoadingContext}
18 * @kind function
19 * @name Provider
20 * @param {object} props Component props.
21 * @param {Cache} props.cache [`Cache`]{@link Cache} instance.
22 * @param {ReactNode} [props.children] React children.
23 * @returns {ReactNode} React virtual DOM node.
24 * @example <caption>Ways to `import`.</caption>
25 * ```js
26 * import { Provider } from 'graphql-react';
27 * ```
28 *
29 * ```js
30 * import Provider from 'graphql-react/public/Provider.js';
31 * ```
32 * @example <caption>Ways to `require`.</caption>
33 * ```js
34 * const { Provider } = require('graphql-react');
35 * ```
36 *
37 * ```js
38 * const Provider = require('graphql-react/public/Provider');
39 * ```
40 * @example <caption>Provide a [`Cache`]{@link Cache} instance for an app.</caption>
41 * ```jsx
42 * import { Cache, Provider } from 'graphql-react';
43 * import React from 'react';
44 *
45 * const cache = new Cache();
46 *
47 * const App = ({ children }) => <Provider cache={cache}>{children}</Provider>;
48 * ```
49 */
50module.exports = function Provider({ cache, children }) {
51 const hydrationTimeStampRef = useRef();
52 if (!hydrationTimeStampRef.current)
53 hydrationTimeStampRef.current = performance.now();
54
55 const loadingRef = useRef();
56 if (!loadingRef.current) loadingRef.current = new Loading();
57
58 if (!(cache instanceof Cache))
59 throw new TypeError('Prop `cache` must be a `Cache` instance.');
60
61 return jsx(HydrationTimeStampContext.Provider, {
62 value: hydrationTimeStampRef.current,
63 children: jsx(CacheContext.Provider, {
64 value: cache,
65 children: jsx(LoadingContext.Provider, {
66 value: loadingRef.current,
67 children,
68 }),
69 }),
70 });
71};