I have a process in my useEffect Hook. I need this process to run 3 time then stop. Also Every time the variable getData (data string from api) changes I need the process to repeat (meaning to run 3 time). The current code works some times and some it keeps going without stopping. Even when getData does not change. It's seem as my if statement is not responding. I don't see console.log('should stop') print. I have checked to see if the value in the if statement is a number and it is. It's just not running the condition
// getData is string that will change from api
// use to stop the setInterval
const getImageCounter = useRef();
useEffect(() => {
let source = axios.CancelToken.source();
let imageCount = 0;
getImageCounter.current = setInterval(() => {
if (imageCount >= 3) {
// stop setInterval when conditions are meet
clearInterval(getImageCounter.current);
console.info('should stop');
}
imageCount++;
console.log('rendering', imageCount);
axios
.get(`${network}/Image`, {
cancelToken: source.token,
})
.then(imageResponse => {
const imageFilter = imageResponse.data.icon.substring(0, imageResponse.data.icon.lastIndexOf('=') + 1); //prettier-ignore
setBase64Image(imageFilter);
})
.catch(function (e) {
if (axios.isCancel(e)) {
console.log(`request cancelled:${e.message}`);
} else {
console.log(
'another error happened fetching overlays:' + e.message,
);
}
});
}, 3000);
return function () {
source.cancel('Cancelling in cleanup');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [getData]);