i want to trigger countdown of 60 seconds when user click from another component . so far i didn’t find any solution
const [seconds, setSeconds] = useState(60) useEffect(() => { console.log(state.Trade.length ,"woking in useeffect "); setInterval(() => { setSeconds(prevState => prevState - 1) }, 1000); }, [state.Trade.length]); // also use without use effect const startCounter = () => { setInterval(() => { setSeconds(prevState => prevState - 1) }, 1000); } if (state.Trade.length!=0) { if (seconds==0) return null startCounter() }else{ return null }
it is not working i search a lot but did not find.Thanks
Advertisement
Answer
Remember to clear your interval
const [seconds, setSeconds] = useState(60); useEffect(() => { const intervalId = setInterval(() => { setSeconds((prevState) => { if(prevState === 1) clearInterval(intervalId) return prevState - 1; }); }, 1000); }, [state.Trade.length]);