Skip to content
CannonReactHooks

useContinueTry

Introduction

A custom React Hook for continuously trying to execute a function.

Play

Clicked: 0

Usage

import { useState } from "react";
import { useContinueTry } from "@cannonui/reacthooks";

const TestUseContinueTry = () => {
  const [count, setCount] = useState<number>(0);
  const fn = () => {
    console.log("count: " + count);
    return count > 10;
  };
  const resolve = useContinueTry(fn, 1000);
  const handleClick = () => {
    setCount((count) => count + 1);
  };
  return (
    <div>
      <button onClick={handleClick}>Click 11 times to resolve</button>
      <div>Clicked: {count}</div>
      <div>{resolve && <span>resolved</span>}</div>
    </div>
  );
};
export default TestUseContinueTry;

Return Value

The hook returns a boolean value indicating whether the function has been successfully executed.

Parameters

NameTypeDescription
fn() => TThe function to be executed.
intervalnumberThe interval (in milliseconds) between retries.

Features

  • Continuously tries to execute the specified function and returns a boolean value indicating whether the function has been successfully executed.
  • Captures errors during the function execution and retries after the specified time interval until the function is successfully executed.

Example

In this example, we have a component called TestUseContinueTry that uses the useContinueTry Hook to continuously try to execute the function fn. When the user clicks the button, the function fn will be called repeatedly until the count variable is greater than 10. During this process, we use the resolve boolean value to track whether the function has been successfully executed.

Use Scenario

The useContinueTry Hook is useful in scenarios where you need to continuously attempt to execute a function and perform certain actions after the function is successfully executed. For example, when you need to fetch data from a server, but network issues might cause the request to fail, you can use this Hook to continuously retry the request function and perform relevant actions once the request is successful.