React JS Chart : Bar Chart not working with Dynamic Data from API

I am working on a Bar Chart using react-chartjs-2 .

It works well with Static Data , but when I set data from API then it is not working.
X Axis data works well but YAxis Data is not working properly.

Below is the code I have tried.

import React, { useState } from "react";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
);

function BarChart() {
  const [labels, setXAxisData] = useState([]);
  const [yAxisData, setYAxisData] = useState([]);

  const [options] = useState({
    plugins: {
      title: {
        display: true,
        text: "Order Summary Data",
      },
    },
    responsive: true,
  });

  setXAxisData(["Jan", "Feb", "March", "April"]);

  setYAxisData([123, 456, 789, 012]); // Data from API

  var [datasets, setDatasets] = useState([
    {
      datasets: yAxisData,
      label: "Invoice Amount",
      backgroundColor: ["rgba(255, 99, 132, 0.8)"],
    },
  ]);

  console.log("Data Sets : ", datasets);

  if (labels && yAxisData) {
    var data = {
      labels,
      datasets,
    };
  }

  console.log("Data Bar : ", data);

  return <Bar options={options} data={data} />;
}

Any help would be great.

  • This answer may help you finding a solution for your issue: stackoverflow.com/a/66302116/2358409

    – 

Leave a Comment