0

I'm currently facing a problem :

After fetching an API response request I wanted to store those informations in tab.

I decided to create an object to get an object tab and after do whatever I want with.

The problem is that when I display the tab I can see what is inside, but when i want to get tab[0] for example, it displays me 'undefined'. I'm quite blocked at this point since i don't really know why my tab[O] is undefined...

Here's the code i use :

let tab = [];

fetch("http://127.0.0.1:8000/api/assets").then(response => {
    response.json().then(data => {
        for(let i = 0 ; i < data.length ; i++){
            let obj = {
                logo: data[i]["symbol"],
                name: data[i]["name"],
                price: data[i]["price"]
            }
            tab.push(obj);
        }
    });
}).catch(
    err => {
        console.log("err: " + err)
    })

console.log(tab)
console.log(tab.length)
console.log(tab[0])

Console display

general.js:218 = console.log(tab)

general.js:219 = console.log(tab.length)

general.js:220 = console.log(tab[0])

n'golo
  • 1
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – pilchard Apr 14 '22 at 12:46
  • Your code goes 1) Declare `tab` 2) Send an asynchronous request that might be resolved at some point in the future. 3) _Immediately_ log the value of `tab` (still undefined) when the promise of data hasn't been resolved. You may find [this answer informative](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). [Maybe also this](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). – Andy Apr 14 '22 at 12:48
  • NOT part of the question but `if (!response.ok) { throw new Error('Network response was not OK'); }` may prove to have value here – Mark Schultheiss Apr 14 '22 at 12:58

2 Answers2

0

You are printing your tab object to the console before the request has had time to finish. Try moving the console.log() statements into your request script after it has received the data:

let tab = [];

fetch("http://127.0.0.1:8000/api/assets").then(response => {
    response.json().then(data => {
        for(let i = 0 ; i < data.length ; i++){
            let obj = {
                logo: data[i]["symbol"],
                name: data[i]["name"],
                price: data[i]["price"]
            }
            tab.push(obj);
        }
        console.log(tab)
        console.log(tab.length)
        console.log(tab[0])
    });
}).catch(
    err => {
        console.log("err: " + err)
    })
Jasper
  • 593
  • 2
  • 23
0

You are checking it before the fetch returns, you need to do it after like such:

let tab = [];

fetch("http://127.0.0.1:8000/api/assets")
  .then(response => {
    response.json().then(data => {
      for (let i = 0; i < data.length; i++) {
        let obj = {
          logo: data[i]["symbol"],
          name: data[i]["name"],
          price: data[i]["price"]
        };
        tab.push(obj);
      }
    })
  })
  .then(function(response) {
    console.log(tab);
    console.log(tab.length);
    console.log(tab[0]);
  })
  .catch(
    err => {
      console.log("err: " + err);
    });
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100