Skip to content

Instantly share code, notes, and snippets.

@savioserra
Created April 29, 2022 20:49
Show Gist options
  • Save savioserra/fb8a2f1abc49c2daddf933530970a4a0 to your computer and use it in GitHub Desktop.
Save savioserra/fb8a2f1abc49c2daddf933530970a4a0 to your computer and use it in GitHub Desktop.
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