@@ -10,6 +10,9 @@ type SetResult<R> = (result: R, asyncState: AsyncState<R>) => AsyncState<R>;
10
10
type SetError < R > = ( error : Error , asyncState : AsyncState < R > ) => AsyncState < R > ;
11
11
12
12
export type UseAsyncOptionsNormalized < R > = {
13
+ initialState : AsyncState < R > ;
14
+ executeOnMount : boolean ;
15
+ executeOnUpdate : boolean ;
13
16
setLoading : SetLoading < R > ;
14
17
setResult : SetResult < R > ;
15
18
setError : SetError < R > ;
@@ -40,6 +43,9 @@ const defaultSetError: SetError<any> = (error, _asyncState) => ({
40
43
} ) ;
41
44
42
45
const DefaultOptions = {
46
+ initialState : InitialAsyncState ,
47
+ executeOnMount : true ,
48
+ executeOnUpdate : true ,
43
49
setLoading : defaultSetLoading ,
44
50
setResult : defaultSetResult ,
45
51
setError : defaultSetError ,
@@ -135,8 +141,15 @@ export const useAsync = <R, Args extends any[]>(
135
141
return promise ;
136
142
} ;
137
143
144
+ // Keep this outside useEffect, because inside isMounted()
145
+ // will be true as the component is already mounted when it's run
146
+ const isMounting = ! isMounted ( ) ;
138
147
useEffect ( ( ) => {
139
- executeAsyncOperation ( ) ;
148
+ if ( isMounting ) {
149
+ normalizedOptions . executeOnMount && executeAsyncOperation ( ) ;
150
+ } else {
151
+ normalizedOptions . executeOnUpdate && executeAsyncOperation ( ) ;
152
+ }
140
153
} , params ) ;
141
154
142
155
return {
0 commit comments