Chart won't update with state change
See original GitHub issueI’m testing an app that toggles a chart between two data objects: chart1
and chart2
. I have an App
component which handles the rendering of a Bar
chart and a Button
. When the Button
is clicked I call a function in App
to update the state to reference either chart1 or chart2 depending on a boolean.
This works successfully the first time I click the button. The state changes in App
and it re-renders the Bar
component with the new data. However, if I click the button again the state doesn’t change and the chart doesn’t update. Only the initial button click does anything. I’ve tested without react-chartjs-2 using plain components and everything works fine - each button click changes the data.
Am I using the Bar
component wrong? I’m passing the state of App
as its props and it works fine initially, then stops updating after the first button click.
import React from 'react';
import ReactDOM from 'react-dom';
import { Bar } from 'react-chartjs-2';
const chart1 = {
labels: ['Team1', 'Team2', 'Team3', 'Team4', 'Team5'],
datasets: [{
label: 'Team points',
data: [503, 385, 270, 133, 65],
backgroundColor: [
'#4DB6AC',
'#E57373',
'#7986CB',
'#F06292',
'#E0E0E0'
]
}]
};
const chart2 = {
labels: ['Team1', 'Team2', 'Team3', 'Team4', 'Team5'],
datasets: [{
label: 'Team points 2',
data: [303, 185, 470, 313, 65],
backgroundColor: [
'#4DB6AC',
'#E57373',
'#7986CB',
'#F06292',
'#E0E0E0'
]
}]
};
const Button = (props) => (
<button id="update-chart" onClick={props.handleOnClick}>Update</button>
);
class App extends React.Component {
constructor(props) {
super(props);
this.handleUpdate = this.handleUpdate.bind(this);
this.updated = false;
this.state = {
chartData: chart1
}
console.log(this.state.chartData);
console.log(this.updated);
}
// Toggle between chart1 and chart2 based on value of updated
handleUpdate() {
const chartData = this.updated ? chart1 : chart2;
this.setState({chartData}, () => {
this.updated = this.updated ? false : true;
console.log(this.state.chartData);
});
}
render() {
return(
<div>
<Bar data={this.state.chartData} width={650} height={400} />
<Button handleOnClick={this.handleUpdate} />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('chart-container')
);
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:12
Top GitHub Comments
I have the same issue and my state change but the chart just update with the first click.
Okay, so you can keep the
chart1
andchart2
where they are and keep thehandleUpdate
the same. Makechart1
andchart2
anonymous functions that return the data object, like this: