Skip to content

Commit 01421bc

Browse files
committed
feat: 🎸 add useUnmountPromise hook
1 parent 36a34e8 commit 01421bc

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/useUnmountPromise.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { useMemo, useRef } from 'react';
2+
3+
export type Race = <P extends Promise<any>, E = any>(promise: P, onError?: (error: E) => void) => P;
4+
5+
const useUnmountPromise = (): Race => {
6+
const refUnmounted = useRef(false);
7+
useRef(() => () => {
8+
refUnmounted.current = true;
9+
});
10+
11+
const wrapper = useMemo(() => {
12+
const race = <P extends Promise<any>, E>(promise: P, onError?: (error: E) => void) => {
13+
const newPromise: P = new Promise((resolve, reject) => {
14+
promise.then(
15+
result => {
16+
if (!refUnmounted.current) resolve(result);
17+
},
18+
error => {
19+
if (!refUnmounted.current) reject(error);
20+
else if (onError) onError(error);
21+
else console.error('useUnmountPromise', error);
22+
}
23+
);
24+
}) as P;
25+
return newPromise;
26+
};
27+
return race;
28+
}, []);
29+
30+
return wrapper;
31+
};
32+
33+
export default useUnmountPromise;

0 commit comments

Comments
 (0)