1

I want to call some function and update state after a time interval in react component but it is not working as expected. Here is my code.

componentDidUpdate(){
        console.log("update")
        setInterval(this.tickingTimer(), 2000)
    }
    tickingTimer(){
        this.state.counter = this.state.counter+1
        console.log("timer");
    }

I tried to set interval function in componentDidMount also but it only call once. It is not updating data after interval.

1 Answer 1

3

You must not mutate state, instead use setState to update state. Also an interval must not be used within componentDidUpdate directly. The best place to have an interval is componentDidMount and the callback function to setInterval must not be triggered but passed as reference.

componentDidMount(){
    console.log("update")
    this.timerId = setInterval(this.tickingTimer, 2000)
}
tickingTimer(){
    this.setState(prev => ({counter: prevState.counter+1}));
    console.log("timer");
}
componentWillUnmount() {
    clearInterval(this.timerId)
}

NOTE: clear setInterval in componentWillUnmount

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.