![](/img/trans.png)
[英]React: How to get loading spinner to show whilst API data loads into my chart.js chart
[英]How to fill my chart (chart.js) with my own data from API
我试图弄清楚如何使用 Axios 用我自己的数据填充我的图表。 这是我拥有的 Chart.js JavaScript 代码:
export const getPieChartData = (themes) => ({
labels: ['Coffee', 'Milk', 'Juice'],
datasets: [{
label: '',
backgroundColor: [themes.primary, themes.warning, themes.danger],
data: [50, 20, 150],
}],
})
我必须用我的 API 中的数据更改“标签”和“数据”数组值,这是我的 API 的样子
"piechart": [
{
"category": "Fashion",
"total": 2000,
"id": 1
},
{
"category": "Sport",
"total": 1000,
"id": 2
},
{
"category": "Business",
"total": 1500,
"id": 3
}
//and other data
]
图表如下所示:在此处输入图像描述
我的朋友在js代码上试过这个,但未能显示数据值:
import axios from 'axios';
const labels = [];
const datas = [];
axios.get('http://localhost:3000/piechart').then((response) => {
// console.log(response.data);
response.data.forEach(element => {
labels.push(element.kategori);
datas.push(element.jumlah);
});
}, (error) => {
console.log(error);
});
export const getPieChartData = (themes) => ({
labels: ["a","b","c"],
datasets: [{
label: '',
backgroundColor: [themes.primary, themes.warning, themes.danger],
data: [1,2,3],
}],
})
您需要在 for 循环中将它们推送到标签和数据中。 我推荐一个像这样简单的for循环
axios.get("localhost:3000/piechart").then(
(response) => {
console.log(response.data);
for (const item of piechart) {
getPieChartData.labels.push(item.category);
getPieChartData.datasets[0].data.push(item.total);
}
},
(error) => {
console.log(error);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.