Skip to content

Commit cb140a0

Browse files
authored
feat: default dependency array for useAsync and useAsyncRetry
2 parents 94b4ea9 + e448d0d commit cb140a0

File tree

4 files changed

+16
-11
lines changed

4 files changed

+16
-11
lines changed

src/__stories__/useAsync.story.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ const fn = () => new Promise<string>((resolve) => {
1010
});
1111

1212
const Demo = () => {
13-
const {loading, value} = useAsync<string>(fn);
13+
const {loading, error, value} = useAsync<string>(fn);
1414

1515
return (
1616
<div>
1717
{loading
1818
? <div>Loading...</div>
19-
: <div>Value: {value}</div>
19+
: error
20+
? <div>Error: {error.message}</div>
21+
: <div>Value: {value}</div>
2022
}
2123
</div>
2224
);

src/__stories__/useAsyncRetry.story.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,13 @@ const DemoRetry = () => {
1919

2020
return (
2121
<div>
22-
{loading?
23-
<div>Loading...</div>
24-
: error?
25-
<div>Error: {error.message}</div>
26-
: <div>Value: {value}</div>
22+
{loading
23+
? <div>Loading...</div>
24+
: error
25+
? <div>Error: {error.message}</div>
26+
: <div>Value: {value}</div>
2727
}
28-
<a href='javascript:void 0' onClick={() => retry()}>Retry</a>
28+
<button onClick={() => retry()}>Retry</button>
2929
</div>
3030
);
3131
};

src/useAsync.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export type AsyncState<T> =
1717
value: T;
1818
};
1919

20-
const useAsync = <T>(fn: () => Promise<T>, deps: DependencyList) => {
20+
const useAsync = <T>(fn: () => Promise<T>, deps: DependencyList = []) => {
2121
const [state, set] = useState<AsyncState<T>>({
2222
loading: true
2323
});

src/useAsyncRetry.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,21 @@ import useAsync, { AsyncState } from './useAsync';
44
export type AsyncStateRetry<T> = AsyncState<T> & {
55
retry():void
66
}
7-
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList) => {
7+
8+
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList = []) => {
89
const [attempt, setAttempt] = useState<number>(0);
9-
const state = useAsync(fn,[...deps, attempt]);
10+
const state = useAsync(fn, [...deps, attempt]);
1011

1112
const stateLoading = state.loading;
1213
const retry = useCallback(() => {
1314
if (stateLoading) {
1415
if (process.env.NODE_ENV === 'development') {
1516
console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.');
1617
}
18+
1719
return;
1820
}
21+
1922
setAttempt(attempt => attempt + 1);
2023
}, [...deps, stateLoading, attempt]);
2124

0 commit comments

Comments
 (0)