-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
use-cache.hooks.ts
90 lines (82 loc) · 2.4 KB
/
use-cache.hooks.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { useRef } from "react";
import { getCommandDispatcher, CommandInstance, Command, getCommandKey } from "@hyper-fetch/core";
import { UseCacheOptionsType, useCacheDefaultOptions, UseCacheReturnType } from "hooks/use-cache";
import { useCommandEvents, useTrackedState } from "helpers";
import { useConfigProvider } from "config-provider";
export const useCache = <T extends CommandInstance>(
command: T,
options: UseCacheOptionsType<T> = useCacheDefaultOptions,
): UseCacheReturnType<T> => {
const { cacheKey, builder } = command;
const { cache, loggerManager } = builder;
const logger = useRef(loggerManager.init("useCache")).current;
const [dispatcher] = getCommandDispatcher(command);
// Build the configuration options
const [globalConfig] = useConfigProvider();
const { dependencyTracking, initialData, deepCompare } = {
...useCacheDefaultOptions,
...globalConfig.useCacheConfig,
...options,
};
/**
* State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
*/
const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<T>({
logger,
command,
dispatcher,
initialData,
deepCompare,
dependencyTracking,
});
/**
* Handles the data exchange with the core logic - responses, loading, downloading etc
*/
const [callbacks] = useCommandEvents({
logger,
actions,
command,
dispatcher,
setCacheData,
});
const revalidate = (invalidateKey?: string | CommandInstance | RegExp) => {
if (invalidateKey instanceof Command) {
cache.revalidate(getCommandKey(invalidateKey, true));
} else if (invalidateKey) {
cache.revalidate(invalidateKey);
} else {
cache.revalidate(cacheKey);
}
};
return {
get data() {
setRenderKey("data");
return state.data;
},
get error() {
setRenderKey("error");
return state.error;
},
get loading() {
setRenderKey("loading");
return state.loading;
},
get status() {
setRenderKey("status");
return state.status;
},
get retries() {
setRenderKey("retries");
return state.retries;
},
get timestamp() {
setRenderKey("timestamp");
return state.timestamp;
},
onCacheError: callbacks.onError,
onCacheSuccess: callbacks.onSuccess,
onCacheChange: callbacks.onFinished,
...actions,
revalidate,
};
};