I have a countdown timer as child element. Once the clock reaches 0 I'm notifying the parent component to update the state to render something else. I'm getting this error in console and I'm not sure how to fix. It also appears to get stuck in a loop. What am I missing?

Error - Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

Path: Clock.jsx (parent)

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeComplete: false
    };
    this.myCallback = this.myCallback.bind(this);
  }

  myCallback = () => {
    this.setState({ timeComplete: true });
  };

  render() {
    let now = new Date();
    now.setSeconds(now.getSeconds() + 2); // timestamp
    now = new Date(now);

    return (
      <div className="container-fluid bg-light h-100">
        <CountdownTimer timerSeconds={now} callbackFromParent={this.myCallback} />
      </div>
    );
  }
}

export default Clock;

Path: CountdownTimer.jsx (child)

class CountdownTimer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { timerSeconds } = this.props;

    const renderer = ({ minutes, seconds, completed }) => {
      if (completed) {
        // Render a completed state
        this.props.callbackFromParent('listInfo');
      }
      return (
        <span>
          {minutes} min {seconds} sec
        </span>
      );
    };
    return <Countdown date={timerSeconds} renderer={renderer} />;
  }
}

export default CountdownTimer;

1 Answers

0
bp123 On

So this is a silly mistake by me but I'm sure others will make it. When you try to update state in the parent component you need to call the function from the child. In this case:

this.props.callbackFromParent('listInfo');

Should have been

this.props.myCallback;