-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
useCacheEntry.mjs
45 lines (33 loc) · 1.21 KB
/
useCacheEntry.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
42
43
44
45
// @ts-check
/** @import { CacheKey, CacheValue } from "./Cache.mjs" */
import React from "react";
import useCache from "./useCache.mjs";
import useForceUpdate from "./useForceUpdate.mjs";
/**
* React hook to get a {@link CacheValue cache value} using its
* {@link CacheKey cache key}.
* @param {CacheKey} cacheKey Cache key.
* @returns {CacheValue} Cache value, if present.
*/
export default function useCacheEntry(cacheKey) {
if (typeof cacheKey !== "string")
throw new TypeError("Argument 1 `cacheKey` must be a string.");
const cache = useCache();
const forceUpdate = useForceUpdate();
const onTriggerUpdate = React.useCallback(() => {
forceUpdate();
}, [forceUpdate]);
React.useEffect(() => {
const eventNameSet = `${cacheKey}/set`;
const eventNameDelete = `${cacheKey}/delete`;
cache.addEventListener(eventNameSet, onTriggerUpdate);
cache.addEventListener(eventNameDelete, onTriggerUpdate);
return () => {
cache.removeEventListener(eventNameSet, onTriggerUpdate);
cache.removeEventListener(eventNameDelete, onTriggerUpdate);
};
}, [cache, cacheKey, onTriggerUpdate]);
const value = cache.store[cacheKey];
React.useDebugValue(value);
return value;
}