how to retry on api error in react in javascript

To retry on an API error in React using Axios, you can wrap your API call in a retry function that will handle the error and retry the call a set number of times. Here is an example of how to do this:

index.tsx
import React, { useState, useEffect } from "react";
import axios from "axios";

const API_URL = "https://example.com/api";

const retry = (fn, retries = 3, delay = 1000) => {
  return fn().catch((error) => {
    if (retries === 0) {
      throw error;
    }
    console.log(`Retrying in ${delay}ms...`);
    return new Promise((resolve) => {
      setTimeout(() => resolve(retry(fn, retries - 1, delay)), delay);
    });
  });
};

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      await retry(async () => {
        const response = await axios.get(API_URL);
        setData(response.data);
        setLoading(false);
      });
    };

    fetchData().catch(() => {
      setError(true);
      setLoading(false);
    });
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error loading data. Please try again later.</div>;
  }

  return (
    <div>
      <h1>API Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default MyComponent;
1193 chars
55 lines

In this example, we define a retry function that takes a function fn as an argument and retries it a set number of times (retries) with a delay between each attempt (delay).

In our useEffect hook, we call retry with an async function that makes the API call using Axios. If the call fails, retry will catch the error and retry the call up to three times with a delay of one second between each attempt.

Finally, we render our component based on the state of loading and error, showing a loading message while the API call is being made and an error message if the call fails after three attempts. Otherwise, we render the data returned by the API call.

gistlibby LogSnag