|
1 |
| -import { useCallback, useState } from 'react'; |
2 |
| -import useAsync from './useAsync'; |
| 1 | +import { useCallback, useState, DependencyList } from 'react'; |
| 2 | +import useAsync, { AsyncState } from './useAsync'; |
3 | 3 |
|
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) => { |
5 | 8 | 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]); |
8 | 10 |
|
| 11 | + const stateLoading = state.loading; |
9 | 12 | const retry = useCallback(() => {
|
10 |
| - if (state.loading) { |
| 13 | + if (stateLoading) { |
11 | 14 | if (process.env.NODE_ENV === 'development') {
|
12 | 15 | console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.');
|
13 | 16 | }
|
14 | 17 | return;
|
15 | 18 | }
|
16 |
| - setAttempt(attempt + 1); |
17 |
| - }, [memoized, state, attempt]); |
| 19 | + setAttempt(attempt => attempt + 1); |
| 20 | + }, [...deps, stateLoading, attempt]); |
18 | 21 |
|
19 | 22 | return { ...state, retry };
|
20 | 23 | };
|
|
0 commit comments