reactjsreact-nativechartsreact-chartjs

Chart not updating after data change in React Chart.js


I made a line chart with React Chart.js. The chart is working perfectly fine but when I try to update the chart, it didn't get updated. Although I am able to change the data of the chart.

I try to update the chart on the legend click. I go through some tutorials and see if update function will help me. But when I try the update function with my line, it shows an error with 'undefined update function'.

import React from "react";

import { Line } from "react-chartjs-2";

const checkinsData = {
  labels: [
    "4 P.M",
    "5 P.M",
    "6 P.M",
    "7 P.M",
    "8 P.M",
    "9 P.M",
    "10 P.M",
    "11 P.M",
    "12 A.M",
    "1 A.M",
    "2 A.M",
    "3 A.M",
    "4 A.M",
  ],
  datasets: [
    {
      label: "Day",
      backgroundColor: "blue",
      borderColor: "#333",
      borderWidth: 2,
      lineTension: 0.1,
      fill: true,
      data: [4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4],
    },
  ],
};

class CheckinGraph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  legendClick = function () {
    console.log("Legend click" + checkinsData.labels);
    checkinsData.datasets.data = [100, 120, 200, 25, 56, 78, 80, 90, 70, 100];
  };
  render() {
    return (
      <div className="col-md-12  default-shadow bg-white pd-30-0 border-radius-10 align-center">
        <Line
          redraw
          data={checkinsData}
          options={{
            title: {
              text: "Total Check-ins",
              fontSize: 20,
              display: true,
            },
            legend: {
              display: true,
              position: "top",
              onClick: this.legendClick,
            },
          }}
        />
      </div>
    );
  }
}

export default CheckinGraph;

Solution

  • Your chart will update/re-render when your component will get new props or state will be updated. Since your chart data that you are updating it not in state of the component, so component don't know about the change and it is not re-rendering your chart. You need to tell the component that something has changed and now time to re-render. This can be achieved by: 1. adding your data in state and then updating the data on click but in a right way (without mutating the state) 2. Added a random key in state and update the state key after updating the non-state data

    state = { key: Date.now() }
    
    
    legendClick=function() {
            console.log("Legend click"+ checkinsData.labels);
            checkinsData.datasets[0].data=[100,120,200,25,56,78,80,90,70,100];
            this.setState({ key: Date.now() });
        }