UNPKG

2.11 kBJavaScriptView Raw
1'use strict';
2
3const { useCallback, useDebugValue, useEffect } = require('react');
4const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
5const useForceUpdate = require('../private/useForceUpdate');
6const useLoading = require('./useLoading');
7
8/**
9 * A React hook to get the [loading cache values]{@link LoadingCacheValue} for
10 * a given [cache key]{@link CacheKey}.
11 * @kind function
12 * @name useLoadingEntry
13 * @param {CacheKey} cacheKey Cache key.
14 * @returns {Set<LoadingCacheValue>|undefined} Loading cache values, if present.
15 * @example <caption>Ways to `import`.</caption>
16 * ```js
17 * import { useLoadingEntry } from 'graphql-react';
18 * ```
19 *
20 * ```js
21 * import useLoadingEntry from 'graphql-react/public/useLoadingEntry.js';
22 * ```
23 * @example <caption>Ways to `require`.</caption>
24 * ```js
25 * const { useLoadingEntry } = require('graphql-react');
26 * ```
27 *
28 * ```js
29 * const useLoadingEntry = require('graphql-react/public/useLoadingEntry');
30 * ```
31 */
32module.exports = function useLoadingEntry(cacheKey) {
33 if (typeof cacheKey !== 'string')
34 throw new TypeError(
35 typeof process === 'object' && process.env.NODE_ENV !== 'production'
36 ? 'Argument 1 `cacheKey` must be a string.'
37 : createArgErrorMessageProd(1)
38 );
39
40 const loading = useLoading();
41 const forceUpdate = useForceUpdate();
42
43 const onTriggerUpdate = useCallback(() => {
44 forceUpdate();
45 }, [forceUpdate]);
46
47 useEffect(() => {
48 const eventNameStart = `${cacheKey}/start`;
49 const eventNameEnd = `${cacheKey}/end`;
50
51 loading.addEventListener(eventNameStart, onTriggerUpdate);
52 loading.addEventListener(eventNameEnd, onTriggerUpdate);
53
54 return () => {
55 loading.removeEventListener(eventNameStart, onTriggerUpdate);
56 loading.removeEventListener(eventNameEnd, onTriggerUpdate);
57 };
58 }, [loading, cacheKey, onTriggerUpdate]);
59
60 const value = loading.store[cacheKey];
61
62 if (typeof process === 'object' && process.env.NODE_ENV !== 'production')
63 // eslint-disable-next-line react-hooks/rules-of-hooks
64 useDebugValue(value);
65
66 return value;
67};