MCPcopy Index your code
hub / github.com/alibaba/hooks / useCachePlugin

Function useCachePlugin

packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts:10–137  ·  view source on GitHub ↗
(
  fetchInstance,
  {
    cacheKey,
    cacheTime = 5 * 60 * 1000,
    staleTime = 0,
    setCache: customSetCache,
    getCache: customGetCache,
  },
)

Source from the content-addressed store, hash-verified

8import { trigger, subscribe } from '../utils/cacheSubscribe';
9
10const useCachePlugin: Plugin<any, any[]> = (
11 fetchInstance,
12 {
13 cacheKey,
14 cacheTime = 5 * 60 * 1000,
15 staleTime = 0,
16 setCache: customSetCache,
17 getCache: customGetCache,
18 },
19) => {
20 const unSubscribeRef = useRef<() => void>(undefined);
21
22 const currentPromiseRef = useRef<Promise<any>>(undefined);
23
24 const _setCache = (key: string, cachedData: CachedData) => {
25 if (customSetCache) {
26 customSetCache(cachedData);
27 } else {
28 setCache(key, cacheTime, cachedData);
29 }
30 trigger(key, cachedData.data);
31 };
32
33 const _getCache = (key: string, params: any[] = []) => {
34 if (customGetCache) {
35 return customGetCache(params);
36 }
37 return getCache(key);
38 };
39
40 useCreation(() => {
41 if (!cacheKey) {
42 return;
43 }
44
45 // get data from cache when init
46 const cacheData = _getCache(cacheKey);
47 if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) {
48 fetchInstance.state.data = cacheData.data;
49 fetchInstance.state.params = cacheData.params;
50 if (staleTime === -1 || Date.now() - cacheData.time <= staleTime) {
51 fetchInstance.state.loading = false;
52 }
53 }
54
55 // subscribe same cachekey update, trigger update
56 unSubscribeRef.current = subscribe(cacheKey, (data) => {
57 fetchInstance.setState({ data });
58 });
59 }, []);
60
61 useUnmount(() => {
62 unSubscribeRef.current?.();
63 });
64
65 if (!cacheKey) {
66 return {};
67 }

Callers

nothing calls this directly

Calls 8

subscribeFunction · 0.90
getCachePromiseFunction · 0.90
setCachePromiseFunction · 0.90
useCreationFunction · 0.85
_getCacheFunction · 0.85
useUnmountFunction · 0.85
_setCacheFunction · 0.85
setStateMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…