Home > Enterprise >  How to call an API every 5 minutes using React?
How to call an API every 5 minutes using React?

Time:02-01

I've been trying to call the API every 5 min but the limit for setInterval doesn't allow that.

useEffect(() => {
    setInterval(() => {
      (() => {
        const API_KEY = "C5EQJXXXXXXXXXXXX";
        const name = "FB";
        axios
          .get(
            `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${name}&interval=5min&apikey=${API_KEY}`
          )
          .then(({ data }) => {
            console.log(data);
            console.log(data["Time Series (5min)"]);
            for (let key in data["Time Series (5min)"]) {
              setStocksX((prev) => [...prev, key]);
              setStocksY((prev) => [
                ...prev,
                data["Time Series (5min)"][key]["1. open"]
              ]);
            }
            //console.log(stocksX, stocksY);
          });
      })();
    }, 30000);
  });

Any advice would be appreciated! Thanks

CodePudding user response:

you can add setInterval with 60 * 5 * 1000 of time, in useEffect hook in first renderization. After you need clear setInterval when unmount component.

const ref = useRef(null)

useEffect(() => {
  ref.current = setInterval(yourFunction, 5 * 60 * 1000);

  return () => {
    if(ref.current){
      clearInterval(ref.current)
    }
  }
}, [])

CodePudding user response:

I presume that your hook is declaring a new setInterval every 0.5 seconds, possibly making your React App stop in order to avoid memory leak, you just need to declare one setInterval, this means that the second parameter of useEffect should have empty squared brackets

  useEffect(() => {
    setInterval(yourFunction, 300000); // The function will be called
  },[]);                               // every 5 minutes

CodePudding user response:

I wrote this utility hook that I use in my React apps all the time:

import React from 'react';

type IntervalCallback = () => void;

function useDispatch(callback: IntervalCallback, delay: number): void {
  const cachedCallback = React.useRef<IntervalCallback>();

  React.useEffect(() => {
    cachedCallback.current = callback;
  }, [callback]);

  React.useEffect(() => {
    if (delay !== 0) {
      const id = setInterval(() => cachedCallback?.current?.(), delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

export const IntervalHooks = {
  useDispatch,
};

I can then use it as such:

IntervalHooks.useDispatch(() => { console.log("hello"); }, 300000);

This gives me a lot of flexibility since I can dynamically update my interval if needed, and takes care of clean up when my component gets unmounted.

  •  Tags:  
  • Related