UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2
3const { useCallback, useEffect } = require('react');
4const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
5const useCache = require('./useCache');
6
7/**
8 * A React hook to load a [cache]{@link Cache#store} entry after becomes
9 * [stale]{@link Cache#event:stale}, if there isn’t loading for the
10 * [cache key]{@link CacheKey} that started after.
11 * @kind function
12 * @name useLoadOnStale
13 * @param {CacheKey} cacheKey Cache key.
14 * @param {Loader} load Memoized function that starts the loading.
15 * @example <caption>Ways to `import`.</caption>
16 * ```js
17 * import { useLoadOnStale } from 'graphql-react';
18 * ```
19 *
20 * ```js
21 * import useLoadOnStale from 'graphql-react/public/useLoadOnStale.js';
22 * ```
23 * @example <caption>Ways to `require`.</caption>
24 * ```js
25 * const { useLoadOnStale } = require('graphql-react');
26 * ```
27 *
28 * ```js
29 * const useLoadOnStale = require('graphql-react/public/useLoadOnStale');
30 * ```
31 */
32module.exports = function useLoadOnStale(cacheKey, load) {
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 if (typeof load !== 'function')
41 throw new TypeError(
42 typeof process === 'object' && process.env.NODE_ENV !== 'production'
43 ? 'Argument 2 `load` must be a function.'
44 : createArgErrorMessageProd(2)
45 );
46
47 const cache = useCache();
48
49 const onCacheEntryStale = useCallback(() => {
50 load();
51 }, [load]);
52
53 useEffect(() => {
54 const eventNameStale = `${cacheKey}/stale`;
55
56 cache.addEventListener(eventNameStale, onCacheEntryStale);
57
58 return () => {
59 cache.removeEventListener(eventNameStale, onCacheEntryStale);
60 };
61 }, [cache, cacheKey, onCacheEntryStale]);
62};