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])
general.js:218 = console.log(tab)
general.js:219 = console.log(tab.length)
general.js:220 = console.log(tab[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)
})
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);
});