Skip to content

Commit bb941b2

Browse files
committed
execute should return a promise and we should also return the current promise from hook
1 parent 4cb214d commit bb941b2

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/index.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,21 @@ const useIsMounted = (): (() => boolean) => {
8383

8484
type UseCurrentPromiseReturn<R> = {
8585
set: (promise: Promise<R>) => void;
86+
get: () => Promise<R> | null;
8687
is: (promise: Promise<R>) => boolean;
8788
};
8889
const useCurrentPromise = <R>(): UseCurrentPromiseReturn<R> => {
8990
const ref = useRef<Promise<R> | null>(null);
9091
return {
9192
set: promise => (ref.current = promise),
93+
get: () => ref.current,
9294
is: promise => ref.current === promise,
9395
};
9496
};
9597

9698
export type UseAsyncReturn<R> = AsyncState<R> & {
97-
execute: () => void;
99+
execute: () => Promise<R>;
100+
currentPromise: Promise<R> | null;
98101
};
99102
export const useAsync = <R, Args extends any[]>(
100103
asyncFunction: (...args: Args) => Promise<R>,
@@ -106,14 +109,14 @@ export const useAsync = <R, Args extends any[]>(
106109
const AsyncState = useAsyncState<R>(normalizedOptions);
107110

108111
const isMounted = useIsMounted();
109-
const CurrentPromise = useCurrentPromise();
112+
const CurrentPromise = useCurrentPromise<R>();
110113

111114
// We only want to handle the promise result/error
112115
// if it is the last operation and the comp is still mounted
113116
const shouldHandlePromise = (p: Promise<R>) =>
114117
isMounted() && CurrentPromise.is(p);
115118

116-
const executeAsyncOperation = () => {
119+
const executeAsyncOperation = (): Promise<R> => {
117120
const promise = asyncFunction(...params);
118121
CurrentPromise.set(promise);
119122
AsyncState.setLoading();
@@ -129,6 +132,7 @@ export const useAsync = <R, Args extends any[]>(
129132
}
130133
}
131134
);
135+
return promise;
132136
};
133137

134138
useEffect(() => {
@@ -138,6 +142,7 @@ export const useAsync = <R, Args extends any[]>(
138142
return {
139143
...AsyncState.value,
140144
execute: executeAsyncOperation,
145+
currentPromise: CurrentPromise.get(),
141146
};
142147
};
143148

0 commit comments

Comments
 (0)