Sinan Samet
Sinan Samet

Reputation: 6752

Updating timer inside render gives warning

I know that it gives me a warning because it's not pure. But when I put it in componentDidMount() it doesn't update. It just reduces once.

This is what I have:

class timer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      seconds: 900
    };

  }

  render() {
    setTimeout(() => {
      if(this.state.seconds > 0){
        this.setState({seconds: this.state.seconds-1})
      }
    }, 1000);
  }
}

How can I update the state somewhere else while still being able to use the setTimeOut() without a warning about that it isn't pure?

Upvotes: 0

Views: 30

Answers (1)

Burak Karasoy
Burak Karasoy

Reputation: 1690

It seems you're trying to decrease one from number every seconds so you should handle that using setinterval method instead of settimeout. If you add it in componentdidmount function it will start decreasing imemdiately after initial rendering occured.

componentDidMount(){
    this.setInterval( () => { 
        if(this.state.seconds > 0){
        this.setState({seconds: this.state.seconds-1})
           })
        }, 1000);
}

Upvotes: 1

Related Questions