0

I fetched data using Axios and useEffect and want to display the it with Chart.js but only the chart frame shows not the data.

Below is my code

 import React, { useState, useEffect } from "react";
 import { Bar, Line } from "react-chartjs-2";
import axios from "axios";

function ChartSix() {

  const [data, setData] = useState([]);
  const [posts, setPosts] = useState([]);

  let title = [];
  let id = [];
  useEffect(() => {

    axios.get("https://jsonplaceholder.typicode.com/posts").then(res => {
      const ipl = res.data;
      setPosts(ipl);

      ipl.forEach(record => {
        title.push(record.title);
        id.push(record.id);
      });

      setData({
        Data: {
          labels: title,
          datasets: [
            {
              label: "IPL 2018/2019 Top Run Scorer",
              data: id,
              backgroundColor: [
                "#3cb371",
                "#0000FF",
                "#9966FF",
                "#4C4CFF",
                "#00FFFF",
                "#f990a7",
                "#aad2ed",
                "#FF00FF",
                "Blue",
                "Red"
              ]
            }
          ]
        }
      });
    });
  });

  return (
    <div>
      <Line data={data}></Line>
    </div>
  );
}

export default ChartSix;

enter image description here

1
  • Do you get any messages in the console? Does it work if you set the same data statically? Do you get the expected response from the API? Commented Feb 27, 2020 at 12:48

1 Answer 1

2

Works with:

  return (
    <div>
      <Line data={data.Data} />
    </div>
  )

https://codesandbox.io/s/frosty-torvalds-qzwt3

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.