Currently, I am in the process of fetching data from an API to later use it for creating a visualization using Chart.js. However, I've encountered a problem while trying to store this retrieved data in arrays and then encountering undefined values when pushing the data.
Below is the function responsible for handling this process:
async function getChartData(){
const xdata = []
const ydata = []
const data = await (await fetch('http://exampleapi.com/api/data')).json()
await data.forEach(async (sensor, index) => {
let sensor_data = await (await fetch(`http://exampleapi.com/api/data/${sensor.name}`)).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 puzzling part is that even after logging the expected output with console.log(xdata)
inside the data.forEach()
, the final result turns out to be undefined.
I am aware that pushing an array in JavaScript involves copying the array reference. To address this issue, I attempted to create copies of the temporary arrays using .slice()
. Despite these efforts, xdata and ydata still show undefined values upon returning them.
Note: For reference, you can see the
console.log(xdata): [output of console.log(xdata)](https://i.exampleimage.net/example.png)
Could someone offer insights on why this behavior is occurring?