I am writing a website using react
. In one component I have a setInterval()
function which gets executed, it updates them DOM
. Now, when I change onto another site with my router (react-router-dom
) the setInterval()
function crashed, because it cannot find the DOM
elements to update. How do I go on about this? I though I use componentWillUnmount()
but the same error occurs.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
stop: false,
}
}
componentWillUnmount() {
if(!this.state.stop) {
this.setState({
stop: true,
})
}
}
_stop = (counter) => {
clearInterval(counter);
}
_someFunc = () => {
...
}
render() {
...
const update = setInterval(function () {
document.getElementById('some-id').innerText = this._someFunc();
}, 1000);
if(this.state.stop) {
this._stop(update)
}
return (
<p id='some-id'></p>
)
}
}
export default Counter;
TypeError: document.getElementById(...) is null.
How do I stop the interval?