react-chartjs-2 icon indicating copy to clipboard operation
react-chartjs-2 copied to clipboard

chart not updating

Open dmichel76 opened this issue 9 years ago • 44 comments

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}/>
    )
  }

}

dmichel76 avatar Jan 03 '17 15:01 dmichel76

The key={Math.random()} gives the same effect as the redraw property.

francisngo avatar Mar 27 '19 19:03 francisngo

I solved it using lodash _.cloneDeep function when switching from one dataset to another.

nejcr avatar Aug 17 '19 18:08 nejcr

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.

bmakan avatar Aug 29 '19 08:08 bmakan

@nealoke thanks, redraw helped me, I was just about to use recharts(Echarts)

theshashiverma avatar Jan 29 '20 11:01 theshashiverma

@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 }
  />
);	

zackster avatar May 09 '20 17:05 zackster

@francisngo

The key={Math.random()} gives the same effect as the redraw property.

No it doesn't, using redraw didn't work properly when the graph height had changed.

marano avatar Jun 10 '20 08:06 marano

@dmichel76 Don't you need to use the redraw prop like so? (This did it for me)

<Line data={this.data} redraw />

This works for me!!!

altaga avatar Jun 29 '20 22:06 altaga

@gor181 Thanks!

just using key={Math.random()} in my chartjs component did the trick.

thanks , this best solution:)

GemsGame avatar Jul 26 '20 10:07 GemsGame

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 avatar Aug 04 '20 22:08 negebauer

@negebauer I've the same problem.

Do you have found a solution?

ambr89 avatar Sep 28 '20 21:09 ambr89

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.

negebauer avatar Sep 28 '20 21:09 negebauer

useEffect(()=>{
let mychart=new Chart(ctx,data)
//do cleanup
return()=>mychart.destroy()
},[])

mahbub-hussain avatar Jan 14 '21 15:01 mahbub-hussain

redraw

just add redraw before closing tag and it would work fine Thank you mahbub-hussain

iar01 avatar Mar 30 '21 10:03 iar01

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?

G-kodes avatar Apr 01 '21 07:04 G-kodes

I just added and redraw/> at the end of Component and the state should update as well in the local Component

iar01 avatar Apr 01 '21 12:04 iar01

@abdullahrafione for me it isn't updating even when I include redraw. Do you know any work arounds for this issue?

parminpatel28 avatar Apr 09 '21 05:04 parminpatel28

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! 😄

perryraskin avatar Jan 07 '22 15:01 perryraskin

The key={Math.random()} gives the same effect as the redraw property.

For me the redraw property ain't working but the key does its job. Such a silly solution though :(

dannypk avatar Jan 28 '22 08:01 dannypk

@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 :)

flogaribal avatar Feb 08 '22 13:02 flogaribal

@dannypk @flogaribal Hi

  1. Do you use immutable data?
  2. Did you try this ?

dangreen avatar Feb 08 '22 13:02 dangreen