Created
April 29, 2022 20:49
-
-
Save savioserra/fb8a2f1abc49c2daddf933530970a4a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
export type RetryCallback<T> = (...args: any[]) => void | T | Promise<T>; | |
function useRetry<T, E = any>(callback: RetryCallback<T>) { | |
const [error, setError] = useState<E>(); | |
const [retryCount, setRetryCount] = useState(0); | |
function watchRetry(callback: RetryCallback<T>) { | |
return async function (...args: any[]) { | |
setError(undefined); | |
try { | |
return await callback(...args); | |
} catch (error) { | |
setError(error as E); | |
setRetryCount((prev) => prev + 1); | |
throw error; | |
} | |
}; | |
} | |
return { execute: watchRetry(callback), retryCount, error }; | |
} | |
export default useRetry; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment