-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Provider.mjs
71 lines (62 loc) · 1.95 KB
/
Provider.mjs
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
61
62
63
64
65
66
67
68
69
70
71
// @ts-check
import React from "react";
import Cache from "./Cache.mjs";
import CacheContext from "./CacheContext.mjs";
import HydrationTimeStampContext from "./HydrationTimeStampContext.mjs";
import Loading from "./Loading.mjs";
import LoadingContext from "./LoadingContext.mjs";
/**
* React component to provide all the React context required to fully enable
* [`graphql-react`](https://npm.im/graphql-react) functionality:
*
* - {@linkcode HydrationTimeStampContext}
* - {@linkcode CacheContext}
* - {@linkcode LoadingContext}
* @param {ProviderProps} props React component props.
* @example
* Provide a {@linkcode Cache} instance for an app:
*
* ```js
* import Cache from "graphql-react/Cache.mjs";
* import Provider from "graphql-react/Provider.mjs";
* import React from "react";
*
* const cache = new Cache();
*
* function App({ children }) {
* return React.createElement(Provider, { cache }, children);
* }
* ```
*/
export default function Provider({ cache, children }) {
const hydrationTimeStampRef = React.useRef(
/** @type {DOMHighResTimeStamp | undefined} */ (undefined)
);
if (!hydrationTimeStampRef.current)
hydrationTimeStampRef.current = performance.now();
const loadingRef = React.useRef(
/** @type {Loading | undefined} */ (undefined)
);
if (!loadingRef.current) loadingRef.current = new Loading();
if (!(cache instanceof Cache))
throw new TypeError("Prop `cache` must be a `Cache` instance.");
return React.createElement(
HydrationTimeStampContext.Provider,
{ value: hydrationTimeStampRef.current },
React.createElement(
CacheContext.Provider,
{ value: cache },
React.createElement(
LoadingContext.Provider,
{ value: loadingRef.current },
children
)
)
);
}
/**
* {@linkcode Provider} React component props.
* @typedef {object} ProviderProps
* @prop {Cache} cache {@linkcode Cache} instance.
* @prop {React.ReactNode} [children] React children.
*/