Skip to content

Commit 929e726

Browse files
committed
fix: fix deps arg and union type in useAsync and useAsyncRetry
1 parent 0a53a56 commit 929e726

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

src/useAsync.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
1-
import { useState, useEffect, useCallback } from 'react';
1+
import { useState, useEffect, useCallback, DependencyList } from 'react';
22

3-
export interface AsyncState<T> {
4-
loading: boolean;
5-
error?: Error;
6-
value?: T;
3+
export type AsyncState<T> =
4+
| {
5+
loading: true;
6+
}
7+
| {
8+
loading: false;
9+
error: Error;
10+
}
11+
| {
12+
loading: false;
13+
error?: undefined;
14+
value: T;
715
};
816

9-
const useAsync = <T>(fn: () => Promise<T>, args?) => {
17+
const useAsync = <T>(fn: () => Promise<T>, deps: DependencyList) => {
1018
const [state, set] = useState<AsyncState<T>>({
1119
loading: true
1220
});
13-
const memoized = useCallback(fn, args);
21+
const memoized = useCallback(fn, deps);
1422

1523
useEffect(() => {
1624
let mounted = true;

src/useAsyncRetry.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
1-
import { useCallback, useState } from 'react';
2-
import useAsync from './useAsync';
1+
import { useCallback, useState, DependencyList } from 'react';
2+
import useAsync, { AsyncState } from './useAsync';
33

4-
const useAsyncRetry = <T>(fn: () => Promise<T>, args: any[] = []) => {
4+
export type AsyncStateRetry<T> = AsyncState<T> & {
5+
retry():void
6+
}
7+
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList) => {
58
const [attempt, setAttempt] = useState<number>(0);
6-
const memoized = useCallback(() => fn(), [...args, attempt]);
7-
const state = useAsync(memoized);
9+
const state = useAsync(fn,[...deps, attempt]);
810

11+
const stateLoading = state.loading;
912
const retry = useCallback(() => {
10-
if (state.loading) {
13+
if (stateLoading) {
1114
if (process.env.NODE_ENV === 'development') {
1215
console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.');
1316
}
1417
return;
1518
}
16-
setAttempt(attempt + 1);
17-
}, [memoized, state, attempt]);
19+
setAttempt(attempt => attempt + 1);
20+
}, [...deps, stateLoading, attempt]);
1821

1922
return { ...state, retry };
2023
};

0 commit comments

Comments
 (0)