-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCacheEntryPrunePrevention.mjs
39 lines (30 loc) · 1.02 KB
/
useCacheEntryPrunePrevention.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
// @ts-check
import React from "react";
import useCache from "./useCache.mjs";
/** @typedef {import("./Cache.mjs").default} Cache */
/** @typedef {import("./Cache.mjs").CacheEventMap} CacheEventMap */
/**
* React hook to prevent a {@link Cache.store cache store} entry from being
* pruned, by canceling the cache entry deletion for
* {@link CacheEventMap.prune `prune`} events with `event.preventDefault()`.
* @param {import("./Cache.mjs").CacheKey} cacheKey Cache key.
*/
export default function useCacheEntryPrunePrevention(cacheKey) {
if (typeof cacheKey !== "string")
throw new TypeError("Argument 1 `cacheKey` must be a string.");
const cache = useCache();
React.useEffect(() => {
const eventNamePrune = `${cacheKey}/prune`;
cache.addEventListener(eventNamePrune, cancelEvent);
return () => {
cache.removeEventListener(eventNamePrune, cancelEvent);
};
}, [cache, cacheKey]);
}
/**
* Cancels an event.
* @param {Event} event Event.
*/
function cancelEvent(event) {
event.preventDefault();
}