Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear setTimeOut when component unmounts

Tags:

javascript

i try to get Items data. if request response less than 1 i have to request again. so i write a recursive function with setTimeout. but when i try to change my route function keeps working. window.clearTimeout() or global.clearTimeOut() not worked here when component unmounts. Do i miss something?

  useEffect(() => {
   getItems(params);
   return () => {
     window.clearTimeout();
     global.clearTimeout();
   }
 }, []);



const getItems = async(params) => {
 try {
  const { data = []} = await axios.get('/some-endpoint',params);
  dispatch({ type: ITEMS_START });
  if (data.length === 0) {
    setTimeout(() => {
      getItems(params);
    }, 5000);
  } else {
    dispatch({ type: ITEMS_SUCCESS, payload: { data } });
  }
 } catch (error) {
  dispatch({ type: ITEMS_ERROR, payload: error });
 }
}
like image 883
ryoshpa Avatar asked Dec 02 '25 17:12

ryoshpa


1 Answers

Use a ref to store the timeout ID and then clear that timeout.

 const timeoutRef = React.useRef();

useEffect(() => {
   getItems(params);
   return () => {
     window.clearTimeout(timeoutRef.current);
   }
 }, []);



const getItems = async(params) => {
 try {
  const { data = []} = await axios.get('/some-endpoint',params);
  dispatch({ type: ITEMS_START });
  if (data.length === 0) {
    timeoutRef.current = setTimeout(() => {
      getItems(params);
    }, 5000);
  } else {
    dispatch({ type: ITEMS_SUCCESS, payload: { data } });
  }
 } catch (error) {
  dispatch({ type: ITEMS_ERROR, payload: error });
 }
}
like image 149
Abdullah Ch Avatar answered Dec 05 '25 07:12

Abdullah Ch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!