Skip to content

Commit 8d59e40

Browse files
committed
add new options to control execution on mount/update and initial async state
1 parent f68bd55 commit 8d59e40

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-async-hook",
3-
"version": "2.0.2",
3+
"version": "2.1.0",
44
"description": "Async hook",
55
"author": "Sébastien Lorber",
66
"license": "MIT",

src/index.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ type SetResult<R> = (result: R, asyncState: AsyncState<R>) => AsyncState<R>;
1010
type SetError<R> = (error: Error, asyncState: AsyncState<R>) => AsyncState<R>;
1111

1212
export type UseAsyncOptionsNormalized<R> = {
13+
initialState: AsyncState<R>;
14+
executeOnMount: boolean;
15+
executeOnUpdate: boolean;
1316
setLoading: SetLoading<R>;
1417
setResult: SetResult<R>;
1518
setError: SetError<R>;
@@ -40,6 +43,9 @@ const defaultSetError: SetError<any> = (error, _asyncState) => ({
4043
});
4144

4245
const DefaultOptions = {
46+
initialState: InitialAsyncState,
47+
executeOnMount: true,
48+
executeOnUpdate: true,
4349
setLoading: defaultSetLoading,
4450
setResult: defaultSetResult,
4551
setError: defaultSetError,
@@ -135,8 +141,15 @@ export const useAsync = <R, Args extends any[]>(
135141
return promise;
136142
};
137143

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();
138147
useEffect(() => {
139-
executeAsyncOperation();
148+
if (isMounting) {
149+
normalizedOptions.executeOnMount && executeAsyncOperation();
150+
} else {
151+
normalizedOptions.executeOnUpdate && executeAsyncOperation();
152+
}
140153
}, params);
141154

142155
return {

0 commit comments

Comments
 (0)