forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseAsyncRetry.ts
29 lines (22 loc) · 840 Bytes
/
useAsyncRetry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* eslint-disable */
import { DependencyList, useCallback, useState } from 'react';
import useAsync, { AsyncState } from './useAsync';
export type AsyncStateRetry<T> = AsyncState<T> & {
retry(): void;
};
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList = []) => {
const [attempt, setAttempt] = useState<number>(0);
const state = useAsync(fn, [...deps, attempt]);
const stateLoading = state.loading;
const retry = useCallback(() => {
if (stateLoading) {
if (process.env.NODE_ENV === 'development') {
console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.');
}
return;
}
setAttempt(currentAttempt => currentAttempt + 1);
}, [...deps, stateLoading]);
return { ...state, retry };
};
export default useAsyncRetry;