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}/>
)
}
}
The key={Math.random()} gives the same effect as the redraw property.
I solved it using lodash _.cloneDeep function when switching from one dataset to another.
I update the chartsjs instance directly. The data comes in via websocket. Inspired by: chartsjs-plugin-streaming.
componentDidMount() {
this.socket = io(window.location.origin, { path: `${window.location.pathname}/ws`, transports: ['websocket'] });
this.socket.on('value_update', ({ a, b }) => {
this.chartsjs.chartInstance.data.datasets[0].data.push({ x: Date.now(), y: a });
this.chartsjs.chartInstance.data.datasets[1].data.push({ x: Date.now(), y: b });
this.chartsjs.chartInstance.update({
preservation: true,
});
}
}
<Line
ref={(chartsjs) => { this.chartsjs = chartsjs; }}
// Set datasets
/>
Not sure if it's correct way to do it performance wise.
@nealoke thanks, redraw helped me, I was just about to use recharts(Echarts)
@bmakan Thank you, was extremely helpful for me to get it working.
In my functional component, I declare
const myChart = createRef();
And inside my websocket logic I have:
myChart.current.chartInstance.data.datasets[0].data.push({
x: Date.now(), y: dataPoint
});
myChart.current.chartInstance.update({
preservation: true,
});
Then I return
return (
<Line
ref={ myChart }
data={ config.data }
options={ config.options }
/>
);
@francisngo
The
key={Math.random()}gives the same effect as theredrawproperty.
No it doesn't, using redraw didn't work properly when the graph height had changed.
@dmichel76 Don't you need to use the
redrawprop like so? (This did it for me)
<Line data={this.data} redraw />
This works for me!!!
@gor181 Thanks!
just using
key={Math.random()}in my chartjs component did the trick.
thanks , this best solution:)
But key={Math.random()} makes it so that every time the component re renders the chart is deleted and created again (since key is used by React as an instance identifier).
Doesn't sound like a solution performance wise 😕
@negebauer I've the same problem.
Do you have found a solution?
We keep the data in state, so that when it changes the component that shows the chart renders again. We don't modify the data object itself directly.
useEffect(()=>{
let mychart=new Chart(ctx,data)
//do cleanup
return()=>mychart.destroy()
},[])
redraw
just add redraw before closing tag and it would work fine Thank you mahbub-hussain
I have just implemented a React Chartjs 2 instance and can confirm this is still an issue, at least for me. I am in an ElectronJS dev setup and have double checked that this seems to be a non-ElectronJS issue as far as I can tell.
const [chartData, setChartData] = useState(null);
// Data Fetch
useEffect(() => {
//...Async fetch my data from file and update state
});
// Attempt at triggering update whenever datasets change:
useEffect(() => {
if (chartData !== null) {
chartRef.current.chartInstance.update({
preservation: true,
});
}
}, [chartData]);
// Nested component to trigger rerender of only the graph for performance
const Graph = () => {
return (
<>
{chartData ? (
<Line data={chartData} options={options} title="Pressure over ticks" ref={chartRef} redraw />
) : null}
</>
);
};
return (
<Graph />
)
Unfortunately, the .update() function does not seem to be doing anything and the chart does not render the chart data unless I resize the application window. I have tried both redraw and without and neither does anything. I have attempted to mix and match to get it to trigger but nothing is doing the trick here? Any ideas?
I just added and redraw/> at the end of Component and the state should update as well in the local Component
@abdullahrafione for me it isn't updating even when I include redraw. Do you know any work arounds for this issue?
Ok so I just had this issue and spent a ton of time on it, until I finally realized what I was doing wrong. I hope this helps anyone on this thread and anyone who also runs into this issue!
Originally I had the chartData set up as a state variable. I realized later that the state was never getting updated so I changed it to a regular variable that gets updated whenever new data is fetched and passed to my custom Chart component. See my Chart component below:
import type { NextPage } from "next"
import React from "react"
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from "chart.js"
import { Line } from "react-chartjs-2"
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
)
interface Props {
labels: string[]
history: number[]
}
const Chart: NextPage<Props> = ({ labels, history }) => {
const chartData = {
labels: labels as never,
datasets: [
{
label: "Last 10 Minutes",
backgroundColor: "#4F1894",
borderColor: "#4F1894",
data: history,
},
],
}
return (
<div className="mt-6 shadow rounded bg-white p-4 sm:p-10">
<Line data={chartData} />
</div>
)
}
export default Chart
The chart gets refreshed any time new data is fetched and passed to this component! 😄
The
key={Math.random()}gives the same effect as theredrawproperty.
For me the redraw property ain't working but the key does its job. Such a silly solution though :(
@gor181 Thanks!
just using
key={Math.random()}in my chartjs component did the trick.
Same for me, redraw isn't working but above solution is. Indeed, a good workaround but not a viable solution :(
My problem was a bit different but related to data update. On first render, chart did not have any data and once fetch was done, the chart was not rendered with the fetched data...
Any better solution welcome :)