chart not updating
I'm trying to get my chart to update dynamically as new data comes in (from socket.io) so I have a method onChange(data) that is used as the callback function of setState called when the new data comes in.
The Chart however does not update itself... unless I refresh/resize the browser. If I set redraw={true}, then the chart updates but it seems to refresh the whole page (?) and kills the performance for the rest of the page...
Any idea what I'm doing wrong here?
import React from 'react'
import ReactDOM from 'react-dom'
import {Line} from 'react-chartjs-2'
module.exports = class MyChart extends React.Component {
constructor(props)
{
super(props)
this.buffersize
this.data = {
labels: [],
datasets: [
{/
label: 'My Chart',
data: []
}
]
}
}
onChange(newdata) {
const size = this.data.datasets[0].data.length
if (size >= this.buffersize)
{
this.data.datasets[0].data.shift()
this.data.labels.shift()
}
this.data.labels.push(newdata.label)
this.data.datasets[0].data.push(newdata.value)
}
render()
{
return (
<Line data={this.data}/>
)
}
}
Here is the code I just tested following your link
const initialData = {
labels: [],
datasets: [
{
id: 0,
data: [],
backgroundColor: chartColors,
color: chartColors,
borderWidth: 0,
},
],
};
const DoughnutChart = (props) => {
const [data, setData] = useState(initialData);
useEffect(() => {
initialData.datasets[0].data = props.data;
initialData.labels = props.labels || [];
setData(initialData)
}, [props.data, props.labels])
const chartOptions = _.merge({
cutout: '80%',
plugins: {
legend: false
}
}, props.options);
return <Doughnut
datasetIdKey='id'
data={data}
options={chartOptions}
/>
}
@flogaribal like everywhere in react you should change data by immutable way.
Thanks a lot, I'm new to React and I never faced this problem, I'll know it!
Here is the new state part of the code. I used lodash but it can be achieved without it
useEffect(() => {
const newData = _.cloneDeep(initialData)
newData.datasets[0].data = props.data;
newData.labels = props.labels || [];
setData(newData)
}, [props.data, props.labels])
Did this issue get any updates or further attention from the authors? I attempted the same (i.e. deep copy and randomising the key) and only randomising the key seems to work for me too. It seems to have been closed after the "chartInstance.update" comment but this is no longer relevant since the update method is no longer exposed.