[Chartjs]-How to update a react-chartjs-2 plot using useState()

2👍

Your code has one bracket too many in the useState hook (or one too little in the updatePlot function). Following code works fine.

Chart.js

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

const Chart = ({ data, options, onUpdate }) => {
  // const dataIn = data[0]; COMMENTED OUT
  // const optionsIn = options[0]; COMMENTED OUT
  // REMOVED onClick function

  return (
    <>
      <div className="header">
        <h1 className="title">Plot</h1>
        <div className="links">
          <a className="btn btn-gh" onClick={onUpdate}>
            Update plot
          </a>
        </div>
      </div>
      <Line data={data} options={options} />
    </>
  );
};

export default Chart;

App.js

import { useState } from "react";
import Chart from "./Chart";

function App() {
  var chartReference = {};

  const data2 = {
    labels: ["1", "2", "3", "4", "5", "6"],
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        fill: false,
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgba(255, 99, 132, 0.2)",
      },
    ],
  };

  const data3 = {
    labels: ["1", "2", "3", "4", "5", "6"],
    datasets: [
      {
        label: "# of Votes",
        data: [3, 2, 5, 3, 19, 12],
        fill: false,
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgba(255, 99, 132, 0.2)",
      },
    ],
  };

  const options2 = {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  };

  const [data, setData] = useState(data2); // REMOVED BRACKETS
  const [options, setOptions] = useState(options2); // REMOVED BRACKETS

  const updatePlot = () => {
    setData(data3);
    setOptions(options2); // This is redundant for the purpose
  };

  return (
    <div class="row">
      <Chart data={data} options={options} onUpdate={updatePlot} />
    </div>
  );
}

export default App;

Leave a comment