1 | ;
|
2 |
|
3 | const { useCallback, useEffect } = require('react');
|
4 | const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
|
5 | const useCache = require('./useCache');
|
6 |
|
7 | /**
|
8 | * A React hook to prevent a [cache]{@link Cache#store} entry from being pruned,
|
9 | * by canceling the cache entry deletion for
|
10 | * [prune events]{@link Cache#event:prune} with `event.preventDefault()`.
|
11 | * @kind function
|
12 | * @name useCacheEntryPrunePrevention
|
13 | * @param {CacheKey} cacheKey Cache key.
|
14 | * @example <caption>Ways to `import`.</caption>
|
15 | * ```js
|
16 | * import { useCacheEntryPrunePrevention } from 'graphql-react';
|
17 | * ```
|
18 | *
|
19 | * ```js
|
20 | * import useCacheEntryPrunePrevention from 'graphql-react/public/useCacheEntryPrunePrevention.js';
|
21 | * ```
|
22 | * @example <caption>Ways to `require`.</caption>
|
23 | * ```js
|
24 | * const { useCacheEntryPrunePrevention } = require('graphql-react');
|
25 | * ```
|
26 | *
|
27 | * ```js
|
28 | * const useCacheEntryPrunePrevention = require('graphql-react/public/useCacheEntryPrunePrevention');
|
29 | * ```
|
30 | */
|
31 | module.exports = function useCacheEntryPrunePrevention(cacheKey) {
|
32 | if (typeof cacheKey !== 'string')
|
33 | throw new TypeError(
|
34 | typeof process === 'object' && process.env.NODE_ENV !== 'production'
|
35 | ? 'Argument 1 `cacheKey` must be a string.'
|
36 | : createArgErrorMessageProd(1)
|
37 | );
|
38 |
|
39 | const cache = useCache();
|
40 |
|
41 | const onCacheEntryPrune = useCallback((event) => {
|
42 | event.preventDefault();
|
43 | }, []);
|
44 |
|
45 | useEffect(() => {
|
46 | const eventNamePrune = `${cacheKey}/prune`;
|
47 |
|
48 | cache.addEventListener(eventNamePrune, onCacheEntryPrune);
|
49 |
|
50 | return () => {
|
51 | cache.removeEventListener(eventNamePrune, onCacheEntryPrune);
|
52 | };
|
53 | }, [cache, cacheKey, onCacheEntryPrune]);
|
54 | };
|