| 6 | }; |
| 7 | |
| 8 | const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList = []) => { |
| 9 | const [attempt, setAttempt] = useState<number>(0); |
| 10 | const state = useAsync(fn, [...deps, attempt]); |
| 11 | |
| 12 | const stateLoading = state.loading; |
| 13 | const retry = useCallback(() => { |
| 14 | if (stateLoading) { |
| 15 | if (process.env.NODE_ENV === 'development') { |
| 16 | console.log( |
| 17 | 'You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.' |
| 18 | ); |
| 19 | } |
| 20 | |
| 21 | return; |
| 22 | } |
| 23 | |
| 24 | setAttempt((currentAttempt) => currentAttempt + 1); |
| 25 | }, [...deps, stateLoading]); |
| 26 | |
| 27 | return { ...state, retry }; |
| 28 | }; |
| 29 | |
| 30 | export default useAsyncRetry; |