I have got an error: Uncaught TypeError: res.data.forEach is not a function
when I use forEach with axios.get. How can I resolve problem?
script:
let totalData = [];
let monthData = [];
$(async function () {
await axios.get(`/dashboard/chart/month`).then((res) => {
console.log(res.data);
res.data.forEach((data) => {
totalData.push(data.total);
monthData.push(data.months);
});
});
});
Data:
{
"success": true,
"data": [
{
"months": "January 21",
"total": 0
},
{
"months": "February 21",
"total": 0
},
{
"months": "March 21",
"total": 0
},
{
"months": "April 21",
"total": 0
}
],
"msg": null
}
CodePudding user response:
Ah, I just realised. Look at your res.data
and you need res.data.data
. Replace your code with:
let totalData = [];
let monthData = [];
$(async function () {
await axios.get(`/dashboard/chart/month`).then((res) => {
console.log(res.data);
// Add another data here:
res.data.data.forEach((data) => {
totalData.push(data.total);
monthData.push(data.months);
});
});
});
The res.data
is the Axios's version. It has your data status and other stuff. You have your data
as well. So you need res.data.data
.