Chartjs-Unable to update state in ReactJS

0๐Ÿ‘

Try Setting the State in the ChartComponent using componentWillReceiveProps lifecycle method .

componentWillReceiveProps (){
 let chartData = this.props.chartData;
    //Check before updating the state to avoid infinite dom updates
    if (chartData.labels.length > 0 && this.state.chartData.labels.length ===0) { 
      this.setState({ chartData: chartData });
    }
}

0๐Ÿ‘

Directly passing this.props.chartData in chart component will trigger a rerender instead of setting a state again in chart component

0๐Ÿ‘

For anyone who might face the same issue, I fixed it by making following changes

  1. I was updating the state and calling the next function one after another. I changed it so that the next function is called in the callback of setState.
  2. In the child component, I added a componentShouldUpdate() function where I added return a false for unnecessary re-renders

Leave a comment