0

I'm trying to fetch data then store them in different arrays. But somehow my result array items are undefined.

Here is the code:

const xData = [];
const yData = [];
const dataStorage = [];
fetch('https://canvasjs.com/services/data/datapoints.php')
.then(response => response.json()
.then(data => { // data is an array
    data.forEach((element) => {
    dataStorage.push({x: element[0], y: element[1]});
    xData.push(element[0]);
    yData.push(element[1]);
   })

}));

console.log(xData[0]) // undefined

Could someone please help explain this to me? Much appreciated!

Lap Hoang
  • 41
  • 5
  • 5
    You order a pizza online. You make order, you try to eat the pizza. It is not there. That is Asynchronous process just like this. That is why there is a promise. It waits for the delivery. – epascarello Jul 31 '20 at 15:26
  • Put your console.log() in your `.then()` block and you should see the result you expect. – elethan Jul 31 '20 at 15:27
  • In order to use `xData`, you will want to run the code/function from within the `promise` (last then). – imvain2 Jul 31 '20 at 15:28
  • @epascarello `orderPizza().then(pizza => eat(pizza))` – VLAZ Jul 31 '20 at 15:29
  • Thanks everyone, that part now I got it. But when I `console.log(xData)` outside the `promise`, I still see an array `[]` then when I click on it, it shows the `xData` content. What's the difference between the array **inside** the `promise` and the one **outside** (which I dont have access to its items)? – Lap Hoang Jul 31 '20 at 15:36

0 Answers0