I am trying to use a periodic function using setInterval
in my react-native app (I am aiming for iOS for now). I am using react-navigation and I would like to stop my interval when I navigate to another screen. To do this I have to use 'clearInterval' outside 'useEffect', here is what I found :https://sebhastian.com/setinterval-react/
const App = () => { const [count, setCount] = useState(0); const [intervalId, setIntervalId] = useState(0); const handleClick = () => { if (intervalId) { clearInterval(intervalId); setIntervalId(0); return; } const newIntervalId = setInterval(() => { setCount(prevCount => prevCount + 1); }, 1000); setIntervalId(newIntervalId); }; return (<div><h1>The component has been rendered for {count} seconds</h1><button onClick={handleClick}> {intervalId ? "Stop counting" : "Start counting"}</button></div> );};
My problem is that when I use the setInterval()
function, it returns a NodeJS.Timer object that is not assignable to my state variable:
Argument of type 'Timer' is not assignable to parameter of type 'SetStateAction<number | undefined>'.ts(2345)
I saw a lot of react native examples using window setInterval()
implicitly so I don't understand why I can't do the same, window object is unknown in my code.Is there a way to "force" react to use window.setInterval()
or is there a workaround with NodeJS.Timer object ?
Thanks in advance.