Home > Back-end >  Facing issue while updating auto increment counter value in react.js using useEffect Hook
Facing issue while updating auto increment counter value in react.js using useEffect Hook

Time:06-13

I'm having an issue with the auto-increment counter, which updates every 2 secs. It updates the value but in a glitchy way Please check the code and share your views regarding the problem.

 const [counter, setCounter] = useState(1200)
 function handleCounter() {
    setCounter(counter   1)
}
useEffect(() => {
    if (counter => 1200 && counter < 1364) {
        setInterval(handleCounter, 2000);
    }else {
        clearInterval(setInterval(handleCounter, 2000))
    }
    clearInterval(setInterval(handleCounter, 2000))
}, [counter])

CodePudding user response:

try this

useEffect(() => {
    const timeInterval = setInterval(() => {
      counter < 1364 && setCounter((prevCount) => prevCount   1);
    }, 2000);

    return () => {
      clearInterval(timeInterval);
    };
  }, [counter]);

CodePudding user response:

The code below will execute the handleCounter function every 2 seconds. Is it what you are trying to do?

  useEffect(() => {
    const intervalID = setInterval(() => handleCounter(), 2000);
    return () => {
      clearInterval(intervalID);
    }
  },[]);
  • Related