logo
  • nextjs
  • react
  • react-query

Fetching API Data at Fibonacci Intervals

August 01, 2024


Here's a tutorial on how to fetch data from an API at intervals based on Fibonacci numbers using React and React Query. The Fibonacci sequence provides a simple and interesting way to vary the fetch interval, increasing it progressively with each call.

Tutorial: Fetching API Data at Fibonacci Intervals

In this tutorial, we will use the Fibonacci sequence to determine the intervals for fetching data from an API. We will use React for the frontend and React Query to manage the data fetching and caching.

Step 1: Setup and Dependencies

Ensure you have the necessary packages installed:

npm install react-query

Step 2: Define the Fibonacci Function

First, we'll define a function to generate Fibonacci numbers up to a maximum value:

const fibonacciUpTo = (max: number) => {
  const fib = [0, 1];
  let nextFib = 0;
 
  while (nextFib <= max) {
    nextFib = fib[fib.length - 1] + fib[fib.length - 2];
    if (nextFib > max) {
      break;
    }
    fib.push(nextFib);
  }
  fib.shift();
  fib.push(max);
  return fib;
};

This function calculates the Fibonacci sequence up to a given maximum value. We then remove the first element (0) as it's not needed for our interval timing and add max number for become a max interval second.

Step 3: Initialize State

Next, we initialize the state to keep track of the current Fibonacci interval and index:

const [fibonacciInterval, setFibonacciInterval] = useState({
  interval: 0,
  index: 0,
});

Step 4: Fetch Data Using React Query

We use the useQuery hook from React Query to fetch data from the API. The interval for fetching is determined by the Fibonacci sequence:

const { isLoading, data } = useQuery(
  "vehicle",
  async () => {
    const response = await fetch(
      "https://random-data-api.com/api/vehicle/random_vehicle"
    );
    return response.json();
  },
  {
    refetchInterval: (data) => {
      if (data?.color === "Red") {
        toast.success("Color is red");
        return false; // Stop fetching if color is red
      }
      return fibonacciInterval.interval * 1000;
    },
    refetchIntervalInBackground: true,
    refetchOnWindowFocus: false,
    onSettled: () => {
      if (fibonacciInterval.index <= fibonacci.length - 1) {
        setFibonacciInterval({
          interval: fibonacci[fibonacciInterval.index],
          index: fibonacciInterval.index + 1,
        });
      }
    },
  }
);

Explanation:

  1. fibonacciUpTo(max): Generates the Fibonacci sequence up to a specified maximum value.
  2. useState: Manages the current interval and index for the Fibonacci sequence.
  3. useQuery: Fetches data from the API at intervals determined by the Fibonacci sequence:
    • The refetchInterval function sets the fetch interval. If the fetched data's color is "Red", it stops further fetching and shows a success message.
    • onSettled: After each fetch, the interval is updated to the next Fibonacci number.

Conclusion

This tutorial demonstrates how to fetch data from an API using intervals based on the Fibonacci sequence. It's a unique way to control the frequency of data fetching, especially useful for scenarios where you want to gradually increase the interval. You can customize the maximum value and behavior based on your needs.