Alberto
Alberto

Reputation: 33

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

I am trying to update a react-chartjs-2 plot passing the new fetch date as props from the App.js to the Chart.js component.

I have created a button, that is linked to a function that calls for a useState in the main app.

Currently I have created two datasets 'data2' and 'data3', and the button should update the plot with the data from 'data3. However whenever I click the button, instead of updating the plot it simply goes blank.

I have the feeling that I am not using the right approach to update the plots but I do not find a lot of information about it.

Chart.js

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



const Chart = ({ data, options, onUpdate }) => {

  const onClick = (e) => {
    e.preventDefault()

    onUpdate()
    console.log(data)
  }

  const dataIn = data[0];
  const optionsIn = options[0];
  
  return(
  <>
    <div className='header'>
      <h1 className='title'>Plot</h1>
      <div className='links'>
        <a
          className='btn btn-gh'
          onClick = {onClick}
        >
          Update plot
        </a>
      </div>
    </div>
    <Line data={dataIn} options={optionsIn} />
  </>
  )
}


export default Chart; 

App.js

import { useState, useEffect } from 'react'
import Chart from './components/Chart'

function App() {

  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
  ])

  const [options, setOptions] = useState([
    options2
  ])


  const updatePlot = () => {
    setData(data3)
    setOptions(options2)
  }


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

  );
}

export default App;

Upvotes: 3

Views: 5126

Answers (1)

scandav
scandav

Reputation: 768

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;

Upvotes: 2

Related Questions