forked from jaydenseric/graphql-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseLoadOnDelete.mjs
41 lines (31 loc) · 1.14 KB
/
useLoadOnDelete.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
// @ts-check
/**
* @import { CacheEventMap, CacheKey } from "./Cache.mjs"
* @import { Loader } from "./types.mjs"
*/
import React from "react";
import useCache from "./useCache.mjs";
/**
* React hook to load a {@link Cache.store cache store} entry after it’s
* {@link CacheEventMap.delete deleted}, if there isn’t loading for the
* {@link CacheKey cache key} that started after.
* @param {CacheKey} cacheKey Cache key.
* @param {Loader} load Memoized function that starts the loading.
*/
export default function useLoadOnDelete(cacheKey, load) {
if (typeof cacheKey !== "string")
throw new TypeError("Argument 1 `cacheKey` must be a string.");
if (typeof load !== "function")
throw new TypeError("Argument 2 `load` must be a function.");
const cache = useCache();
const onCacheEntryDelete = React.useCallback(() => {
load();
}, [load]);
React.useEffect(() => {
const eventNameDelete = `${cacheKey}/delete`;
cache.addEventListener(eventNameDelete, onCacheEntryDelete);
return () => {
cache.removeEventListener(eventNameDelete, onCacheEntryDelete);
};
}, [cache, cacheKey, onCacheEntryDelete]);
}