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>
);
}
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
);