Reputation: 21
im learning React and trying to display random images from https://picsum.photos/ i
m using their API to get a list of random images, this is a JSON file containing some info, im interested only in the images URL. it seems like my array is filled with the url
s but i cant access them.
i have tried logging step by step some of my issues, it seems like my array is getting filled with strings, but in the end i cant get any access to them, if i fill the list manuallt , lets say
const array = [1,2,3]
it will log the values like array[0] .
why cant i access the strings which was pushed into the array with my JSON callback function?
Upvotes: 2
Views: 75
Reputation: 84
Hi, please remember that js is asynchronous ( you have to wait for the response, in order to console.log it ). This is the reason why you get list undefined
.
I advise you to use fetch instead of loadJSON. Here is a code snippet:
const url = "https://picsum.photos/v2/list"
let list = []
async function init() {
let data = await fetch(url).then(res => res.text())
let data_list = JSON.parse(data)
for(el of data_list){
list.push(el.url)
}
console.log("list:",list)
console.log("list.length:",list.length)
}
init()
For example:
let list = []
loadJSON(...()=>{
....
list = ["element1","element2"]
})
console.log(list) // list will be undefined
You would have to wait for loadJson
to populate the list. This is due to the fact that javascript will run the function loadJSON
, but it will not wait for it to finish, and will continue to run the rest of the code.
When the line console.log(list)
is executed, if loadJSON
has not finished yet, list
array will be undefined
.
Upvotes: 1
Reputation: 11
That's because you're initializing the array with 30 empty elements and the indexes you're trying to console log are within that first 30 empty elements anyway. Look at the indexes in the browser console, they start at 30, so if you actually try to console.log(list[55])
you will get a defined value.
Remove the 30
from the list constant and it will work.
Upvotes: 0