Published on

useContinousRetry Hook React

useContinousRetry Hook React

useContinousRetry Hook React

useContinousRetry Code and Usage

useContinousRetry is a hook to handle continuous retries of an action, such as making an API call.

import { useState, useEffect } from "react";

const useContinuousRetry = (action, interval) => {
  const [isRetrying, setIsRetrying] = useState(false);

  useEffect(() => {
    let retryTimer;

    const retryAction = async () => {
      setIsRetrying(true);
      try {
        await action();
      } catch (error) {
        console.error("API call failed:", error);
        retryTimer = setTimeout(retryAction, interval);
      } finally {
        setIsRetrying(false);
      }
    };

    retryAction();

    return () => {
      clearTimeout(retryTimer);
    };
  }, [action, interval]);

  return isRetrying;
};

// Usage
const ContinuousRetryExample = () => {
  const mockApiCall = async () => {
    const randomValue = Math.random();
    if (randomValue > 0.7) {
      return "Success!";
    } else {
      throw new Error("API call failed.");
    }
  };

  const isRetrying = useContinuousRetry(mockApiCall, 2000);

  return <div>{isRetrying ? <p>Retrying...</p> : <p>Not retrying.</p>}</div>;
};