-3

I am trying to render a graph with data from an api rest, but it is not showing the values. I've tried to check the chartjs documentation and I can't find the error. can anybody help me? I'm using react, chart and axios.

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

export default function ChartBar() {
  const [dados, setDados] = useState({});

  async function consultApi() {
    let res = await axios.get(
      "https://private-afe609-testefront.apiary-mock.com/anual-result"
    );
    Object.values(res.data).map(item => setDados(item));

  }
  console.log(dados);

  consultApi();

  return (
    <div>
      <Bar labels={[dados.label]} data={[dados.value]} />
    </div>
  );
}
  • This same question is asked hundreds of times each and every single day. Why didn't you read the existing answer? – JK. Mar 17 '20 at 02:28

1 Answers1

-1

I think you're missing a lot of stuff here

Check how the chart js 2 retrieve data props and how you are processing the API response.

This'll work

Check here for sandbox

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

export default function App() {
  const [label, setLabel] = useState([]);
  const [data, setData] = useState([]);

  React.useEffect(() => {
    axios
      .get("https://private-afe609-testefront.apiary-mock.com/anual-result")
      .then(result => {
        setLabel(Object.keys(result.data).map(key => result.data[key].label));
        setData(Object.keys(result.data).map(key => result.data[key].value));
        console.log(data);
      });
  }, []);

  return (
    <div>
      <Bar data={{
        labels: label,
        datasets: [
          {
            label: 'My First dataset',
            backgroundColor: 'rgba(255,99,132,0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1,
            hoverBackgroundColor: 'rgba(255,99,132,0.4)',
            hoverBorderColor: 'rgba(255,99,132,1)',
            data: data
          }
        ]
      }} />
    </div>
  );
}


const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);
Robert Tirta
  • 2,593
  • 3
  • 18
  • 37