0

I'm using ZingChart to visually represent data, but it seems that the chart is not updating when state changes.

My chart config is very simple:

//in constructor()
const { data } = props;
this.state = {
    chartConfig: {
        type: 'area',
        series: [
            {values: this.updateValues(data)}
        ]
    }
};

updateValues() returns the values that will be displayed, it works fine.

Now when the parent component changes, it send some new props which I will use to set a new state with :

componentDidUpdate(prevProps) {
    if (this.props.data !== prevProps.data) {
    const chartConfig = { ...this.state.chartConfig };
    chartConfig.series[0].values = this.updateValues(this.props.data);

    this.setState({ chartConfig });

    console.log(this.state.chartConfig); //<--- state successfully updated
    }
}

And this is the render method, I first check if state has been updated (since setState is async) and it seems okay.

render() { 
    return (
        <React.Fragment>
            {this.state.chartConfig.series[0].values.length} {/* <--- state here is also up to date */}
            <ZingChart data={this.state.chartConfig}/> {/* but not the chart */}
        </React.Fragment>
    );
}

The problem now is that the chart is not directly updating when state changes, (until I force refresh), so what may be causing this issue? They say in the blog that the chart is reactive to component changes, but it does not seem the case.

Thanks!

adxl
  • 829
  • 1
  • 9
  • 19

1 Answers1

0

@adxl In your code, the componentDidUpdate method contains a spread of this.state.config.

const chartConfig = { ...this.state.chartConfig };

Since this actually maintains a shallow reference to its contents, modifying the values array is passed by reference. If you were to deep clone the config object, then it would work.

const chartConfig = Object.assign({}, this.state.chartConfig);

MDN Docs here -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

nardecky
  • 2,623
  • 8
  • 18