Skip to content

Commit e15f649

Browse files
committed
feat: cache and executation control
1 parent f5aa4fb commit e15f649

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

src/treeReactApp/utils/usePromise.ts

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
1-
import { useState, useEffect, useCallback } from 'react';
1+
import { useState, useEffect, useCallback, useMemo } from 'react';
22

3-
const cache = new Set();
3+
const usePromiseCache = new Map<FunctionReturningPromise, Map<string, any>>();
44

55
// These typings are borrowed from @raycast/utils package
66
type PromiseType<P extends Promise<any>> = P extends Promise<infer T> ? T : never;
77
type FunctionReturningPromise<T extends any[] = any[]> = (...args: T) => Promise<any>;
88
type PromiseReturnType<T extends FunctionReturningPromise> = PromiseType<ReturnType<T>>;
99

10+
type UsePromiseOptions = {
11+
execute?: boolean;
12+
};
13+
1014
// Thank you Copilot
1115
export const usePromise = <T extends FunctionReturningPromise>(
1216
promise: T,
13-
deps: any[] = []
17+
deps: any[] = [],
18+
{ execute = true }: UsePromiseOptions = {}
1419
): {
1520
data: PromiseReturnType<T> | undefined;
1621
error: Error | undefined;
@@ -21,25 +26,40 @@ export const usePromise = <T extends FunctionReturningPromise>(
2126
const [error, setError] = useState<Error>();
2227
const [isValidating, setIsValidating] = useState(false);
2328

29+
const cachedKey = useMemo(() => {
30+
return deps.map((dep) => dep.toString()).join('');
31+
}, [deps]);
32+
2433
const mutate = useCallback(() => {
34+
const currentData = usePromiseCache.get(promise)?.get(cachedKey);
35+
36+
if (currentData) {
37+
setData(currentData);
38+
}
39+
2540
setIsValidating(true);
2641
promise()
2742
.then((data) => {
2843
setData(data);
2944
setIsValidating(false);
45+
46+
if (!usePromiseCache.has(promise)) {
47+
usePromiseCache.set(promise, new Map());
48+
}
49+
50+
usePromiseCache.get(promise)?.set(cachedKey, data);
3051
})
3152
.catch((error) => {
3253
setError(error);
3354
setIsValidating(false);
3455
});
35-
}, [promise]);
56+
}, [cachedKey, promise]);
3657

3758
useEffect(() => {
38-
if (!cache.has(promise)) {
39-
cache.add(promise);
59+
if (execute) {
4060
mutate();
4161
}
42-
}, deps);
62+
}, [execute, mutate]);
4363

4464
return {
4565
data,

0 commit comments

Comments
 (0)