Home > Back-end >  how to clear setTimeOut when component unmounts
how to clear setTimeOut when component unmounts

Time:06-17

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 });
 }
}

CodePudding user response:

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 });
 }
}

CodePudding user response:

Create a reference you can set your timeout too that the unmount can call back to.

let timeout = null;

useEffect(() => {
    getItems();
    return () => {
      if(timeout)
        clearTimeOut(timeout)
    }
})

const getItems = () => {
    timeout = setTimeOut(() => work, 5000);
}

This is the general idea.

CodePudding user response:

Each SetTimeout ( and setInterval ) returns a number which can be used to clear it. ie, var x = setTimeout(() => console.log('timeout'),1000); clearTimeout(x); will do nothing.

  • Related