Search code examples
reactjsstatecountdownsetstate

React: setState with Countdown


I have a state counter in my main App.js class. Also I have a Countdown.js, which updates the counter of his parent class every time he has finished. But i get an Error, when the timer finished once. Also, state counter jumps from 0 to 2 and not from 0 to 1...

Warning: Cannot update during an existing state transition (such as within `render`).

How can i get rid of this error? Or do you have a solution how to count++, when the timer is finished?

My class App.js:

import React from "react"
import "./App.css"
import Countdown from "./Countdown.js"

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      counter: 0
    };
    this.count = this.count.bind(this);
  }

  count() {
    this.setState(prevState => ({
      count: prevState.counter++
    }));
  }

  render() {
    return (
      <div className="window">
        <p>{this.state.counter}</p>
        <Countdown count={this.count} />
      </div>
    );
  }
}

export default App

My Countdown.js

import React from "react";
import CountDown from "react-countdown";

class CountdownQuestion extends React.Component {
  constructor() {
    super();
    this.state = {
      time: 3000
    };
  }

  render() {
    const renderer = ({ seconds, completed }) => {
      if (completed) {
        this.props.count();
        return <h2>Zeit abgelaufen</h2>;
      } else {
        return <h3>{seconds}</h3>;
      }
    };

    return (
      <CountDown date={Date.now() + this.state.time} renderer={renderer} />
    );
  }
}

export default CountdownQuestion;

Solution

  • Well, it's exactly like the error says. You can't update state (like in your count() function) during a render. You're probably better of using the onComplete hook.

    class CountdownQuestion extends React.Component {
      constructor() {
        super();
        this.state = {
          time: 3000
        };
      }
    
      render() {
        // Removing this.props.count() from this function also keeps it more clean and focussed on the rendering.
        const renderer = ({ seconds, completed }) => {
          if (completed) {
            return <h2>Zeit abgelaufen</h2>;
          } else {
            return <h3>{seconds}</h3>;
          }
        };
    
        return (
          <CountDown
            date={Date.now() + this.state.time}
            onComplete={this.props.count} // <-- This will trigger the count function when the countdown completes.
            renderer={renderer}
          />
        );
      }
    }