1π
I donβt know much about React but I know that react-chartjs-2 is a wrapper for Chart.js. When using Chart.js directly, the preferred method to update a chart is to invoke chart.update()
once the chart data or its options have changed.
Therefore, in your code, your could do the same each time you want the chart be re-drawn on its canvas
.
To do so, you first need to obtain a reference to the Chart.js instance as explained here.
constructor() {
...
this.chartReference = React.createRef();
...
}
componentDidMount() {
this.chart = this.chartReference.current.chartInstance;
...
}
render() {
return (
<Bar
ref={this.chartReference}
...
/>
);
}
Your bubbleSort
method could then be split into the following separate methods and it should work as expected.
bubbleSort() {
let data = this.chart.data.datasets[0].data;
let swapped;
let timeout = 0;
do {
swapped = false;
for (let i = 0; i < data.length; i++) {
if (data[i] > data[i + 1]) {
let tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
timeout += 100;
this.updateChartDelayed(data.slice(0), timeout);
swapped = true;
}
}
} while (swapped);
}
updateChartDelayed(data, timeout) {
this.timer = setTimeout(() => {
this.chart.data.datasets[0].data = data;
this.chart.update();
}, timeout);
}
Please take a look at this StackBlitz and see how it works.
Source:stackexchange.com