(
fn: T,
deps: DependencyList = [],
initialState: StateFromFunctionReturningPromise<T> = { loading: false }
)
| 34 | ]; |
| 35 | |
| 36 | export default function useAsyncFn<T extends FunctionReturningPromise>( |
| 37 | fn: T, |
| 38 | deps: DependencyList = [], |
| 39 | initialState: StateFromFunctionReturningPromise<T> = { loading: false } |
| 40 | ): AsyncFnReturn<T> { |
| 41 | const lastCallId = useRef(0); |
| 42 | const isMounted = useMountedState(); |
| 43 | const [state, set] = useState<StateFromFunctionReturningPromise<T>>(initialState); |
| 44 | |
| 45 | const callback = useCallback((...args: Parameters<T>): ReturnType<T> => { |
| 46 | const callId = ++lastCallId.current; |
| 47 | |
| 48 | if (!state.loading) { |
| 49 | set((prevState) => ({ ...prevState, loading: true })); |
| 50 | } |
| 51 | |
| 52 | return fn(...args).then( |
| 53 | (value) => { |
| 54 | isMounted() && callId === lastCallId.current && set({ value, loading: false }); |
| 55 | |
| 56 | return value; |
| 57 | }, |
| 58 | (error) => { |
| 59 | isMounted() && callId === lastCallId.current && set({ error, loading: false }); |
| 60 | |
| 61 | return error; |
| 62 | } |
| 63 | ) as ReturnType<T>; |
| 64 | }, deps); |
| 65 | |
| 66 | return [state, callback as unknown as T]; |
| 67 | } |
no test coverage detected
searching dependent graphs…