0

I'm trying to stop axios request. I use useInterval(custom hooks)(I referenced a website) to request api. So I stop it with useState and it's totally stopped when i set interval like 1000ms. however, when i set interval like 100ms then i can't stop api request. it's stopped after 3seconds or something. So i tried to use if statement. but it's not working as i expected.

and I also checked Network from development tool on chrome and the request Status was getting changed from pending to 200 and when all the request's Status change to 200, then it stopped.

I really want to know how i can stop API request properly.

my code is like this

useInterval

import { useEffect } from "react";
import { useRef } from "react";

const useInterval = (callback, delay) => {
  const savedCallback = useRef(callback);

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

  useEffect(() => {
    const tick = () => {
      savedCallback.current();
    };

    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};

export default useInterval;

API calling

  const [API_DATA, setAPI_DATA] = useState(null);
  const [apiStart, setApiStart] = useState(false);
  const [spinner, setSpinner] = useState(false);
  //Request API 
  const getAPI = useCallback(async () => {
    if (apiStart) {
      await axios
        .get(API_URL, {
          headers: Header,
        })
        .then(response => {
          setAPI_DATA(response.data);
          setSpinner(false);
        })
        .catch(error => {
          init();
          console.log("error");
        });
    }
  }, [API_DATA,  spinner]);
  
  // start API 
    const start_API = () => {
    setSpinner(true);
    setApiStart(true);
  };
  
 //stop API 
   const stop_API = () => {
    setSpinner(false);
    alert("API STOP");
    setApiStart(false);
  };
  
 //using useInterval
    useInterval(
    () => {
      if (apiStart) return getAPI();
    },
    apiStart ? 100 : null
  );
Somi
  • 141
  • 6

0 Answers0