-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
useLoadingEntry.mjs
49 lines (37 loc) · 1.33 KB
/
useLoadingEntry.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
46
47
48
49
// @ts-check
/**
* @import { CacheKey } from "./Cache.mjs"
* @import LoadingCacheValue from "./LoadingCacheValue.mjs"
*/
import React from "react";
import useForceUpdate from "./useForceUpdate.mjs";
import useLoading from "./useLoading.mjs";
/**
* React hook to get the {@link LoadingCacheValue loading cache values} for a
* given {@link CacheKey cache key}.
* @param {CacheKey} cacheKey Cache key.
* @returns {Set<LoadingCacheValue> | undefined} Loading cache values, if
* present.
*/
export default function useLoadingEntry(cacheKey) {
if (typeof cacheKey !== "string")
throw new TypeError("Argument 1 `cacheKey` must be a string.");
const loading = useLoading();
const forceUpdate = useForceUpdate();
const onTriggerUpdate = React.useCallback(() => {
forceUpdate();
}, [forceUpdate]);
React.useEffect(() => {
const eventNameStart = `${cacheKey}/start`;
const eventNameEnd = `${cacheKey}/end`;
loading.addEventListener(eventNameStart, onTriggerUpdate);
loading.addEventListener(eventNameEnd, onTriggerUpdate);
return () => {
loading.removeEventListener(eventNameStart, onTriggerUpdate);
loading.removeEventListener(eventNameEnd, onTriggerUpdate);
};
}, [loading, cacheKey, onTriggerUpdate]);
const value = loading.store[cacheKey];
React.useDebugValue(value);
return value;
}