@@ -83,18 +83,21 @@ const useIsMounted = (): (() => boolean) => {
83
83
84
84
type UseCurrentPromiseReturn < R > = {
85
85
set : ( promise : Promise < R > ) => void ;
86
+ get : ( ) => Promise < R > | null ;
86
87
is : ( promise : Promise < R > ) => boolean ;
87
88
} ;
88
89
const useCurrentPromise = < R > ( ) : UseCurrentPromiseReturn < R > => {
89
90
const ref = useRef < Promise < R > | null > ( null ) ;
90
91
return {
91
92
set : promise => ( ref . current = promise ) ,
93
+ get : ( ) => ref . current ,
92
94
is : promise => ref . current === promise ,
93
95
} ;
94
96
} ;
95
97
96
98
export type UseAsyncReturn < R > = AsyncState < R > & {
97
- execute : ( ) => void ;
99
+ execute : ( ) => Promise < R > ;
100
+ currentPromise : Promise < R > | null ;
98
101
} ;
99
102
export const useAsync = < R , Args extends any [ ] > (
100
103
asyncFunction : ( ...args : Args ) => Promise < R > ,
@@ -106,14 +109,14 @@ export const useAsync = <R, Args extends any[]>(
106
109
const AsyncState = useAsyncState < R > ( normalizedOptions ) ;
107
110
108
111
const isMounted = useIsMounted ( ) ;
109
- const CurrentPromise = useCurrentPromise ( ) ;
112
+ const CurrentPromise = useCurrentPromise < R > ( ) ;
110
113
111
114
// We only want to handle the promise result/error
112
115
// if it is the last operation and the comp is still mounted
113
116
const shouldHandlePromise = ( p : Promise < R > ) =>
114
117
isMounted ( ) && CurrentPromise . is ( p ) ;
115
118
116
- const executeAsyncOperation = ( ) => {
119
+ const executeAsyncOperation = ( ) : Promise < R > => {
117
120
const promise = asyncFunction ( ...params ) ;
118
121
CurrentPromise . set ( promise ) ;
119
122
AsyncState . setLoading ( ) ;
@@ -129,6 +132,7 @@ export const useAsync = <R, Args extends any[]>(
129
132
}
130
133
}
131
134
) ;
135
+ return promise ;
132
136
} ;
133
137
134
138
useEffect ( ( ) => {
@@ -138,6 +142,7 @@ export const useAsync = <R, Args extends any[]>(
138
142
return {
139
143
...AsyncState . value ,
140
144
execute : executeAsyncOperation ,
145
+ currentPromise : CurrentPromise . get ( ) ,
141
146
} ;
142
147
} ;
143
148
0 commit comments