UNPKG

2.02 kBJavaScriptView Raw
1'use strict';
2
3const { useCallback, useDebugValue, useEffect } = require('react');
4const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
5const useForceUpdate = require('../private/useForceUpdate');
6const useCache = require('./useCache');
7
8/**
9 * A React hook to get a [cache value]{@link CacheValue} using its
10 * [cache key]{@link CacheKey}.
11 * @kind function
12 * @name useCacheEntry
13 * @param {CacheKey} cacheKey Cache key.
14 * @returns {CacheValue} Cache value, if present.
15 * @example <caption>Ways to `import`.</caption>
16 * ```js
17 * import { useCacheEntry } from 'graphql-react';
18 * ```
19 *
20 * ```js
21 * import useCacheEntry from 'graphql-react/public/useCacheEntry.js';
22 * ```
23 * @example <caption>Ways to `require`.</caption>
24 * ```js
25 * const { useCacheEntry } = require('graphql-react');
26 * ```
27 *
28 * ```js
29 * const useCacheEntry = require('graphql-react/public/useCacheEntry');
30 * ```
31 */
32module.exports = function useCacheEntry(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 cache = useCache();
41 const forceUpdate = useForceUpdate();
42
43 const onTriggerUpdate = useCallback(() => {
44 forceUpdate();
45 }, [forceUpdate]);
46
47 useEffect(() => {
48 const eventNameSet = `${cacheKey}/set`;
49 const eventNameDelete = `${cacheKey}/delete`;
50
51 cache.addEventListener(eventNameSet, onTriggerUpdate);
52 cache.addEventListener(eventNameDelete, onTriggerUpdate);
53
54 return () => {
55 cache.removeEventListener(eventNameSet, onTriggerUpdate);
56 cache.removeEventListener(eventNameDelete, onTriggerUpdate);
57 };
58 }, [cache, cacheKey, onTriggerUpdate]);
59
60 const value = cache.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};