So I'm trying to retrieve some data that I'm fetching from an api so that I can build a chart with Chart.js with that retrieved data.
The problem is that I am declaring 2 arrays to store the data returned by the api, but when I push the data it returns undefined and I can't understand why.
Here's the function responsible for what I described above:
async function getChartData(){
const xdata = []
const ydata = []
const data = await (await fetch('http://projetoti.test/api/api.php?nome=all')).json()
await data.forEach(async (sensor, index) => {
let sensor_data = await (await fetch(`http://projetoti.test/api/api.php?nome=${sensor.name}&history=true`)).json()
let xtemp_arr = []
let ytemp_arr = []
Object.keys(sensor_data).forEach(sData => {
xtemp_arr.push(sensor_data[sData].value)
ytemp_arr.push(sensor_data[sData].time)
})
xdata.push(xtemp_arr.slice())
ydata.push(ytemp_arr.slice())
})
console.log(xdata)
return { xdata, ydata}
}
The confusing part is, when I console.log(xdata)
inside the data.forEach()
it consoles the expected even when it quits the forEach() xdata consoles the expected but it returns undefined.
I know that in JavaScript when we push an array what is actually happening is that the reference of the array is being copied.
So I tried to solve that by making a copy of the temporary arrays with .slice()
.
But still, xdata and ydata are returning undefined.
Note: Here is the print of the console.log(xdata): [output of console.log(xdata)](https://i.stack.imgur.com/Theuh.png)
Can anyone help me understand why this is happening?