-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
useLoadOnStale.mjs
41 lines (31 loc) · 1.13 KB
/
useLoadOnStale.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 becomes
* {@link CacheEventMap.stale stale}, 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 useLoadOnStale(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 onCacheEntryStale = React.useCallback(() => {
load();
}, [load]);
React.useEffect(() => {
const eventNameStale = `${cacheKey}/stale`;
cache.addEventListener(eventNameStale, onCacheEntryStale);
return () => {
cache.removeEventListener(eventNameStale, onCacheEntryStale);
};
}, [cache, cacheKey, onCacheEntryStale]);
}