Error: Maximum update depth exceeded. React state

Viewed 92

I am getting this error I guess due to bursting up the react's state but I don't know what is wrong going on here.

So I have parent-child relationship components as you can see below:

PARENT Component

class App extends Component {
    constructor(props){
        super(props);
        this.state={
            parentTime: 0,
        }
    };
    
    
    changeTimeState(childTime){
        //this.setState({parentTime: childTime})
        console.log("Parent state time: ",childTime)
    }
    render() {
        return (
            <div className="box">
                <Child time={this.state.parentTime} changeTime={this.changeTimeState.bind(this)}/>
            </div>
        );
    }
}

CHILD Component

class Child extends Component {
    constructor(props){
        super(props)
        this.state = {
            childTime: props.time
        }
    }

    componentDidMount(){
            if (this.state){
                setInterval(()=>{
                    this.setState({childTime: this.state.childTime+1})
                },1000)
            }
        }
    
    render() {
        return (
            <div newTime={this.props.changeTime(this.state.childTime)}/>
        );
    }
}

I am passing data in between them and uncommenting this.setState({parentTime: childTime}) in parent component causes that error. This is where I need help to understand and fix it.

1 Answers
i don't know is it what you wanted 

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      childTime: props.time,
    };
  }

  componentDidMount() {
    if (this.state) {
      setInterval(() => {
        this.setState({ childTime: this.state.childTime + 1 });
        this.props.changeTime(this.state.childTime);
      }, 1000);
    }
  }

  render() {
    return <div />;
  }
}
Related