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?
CodePudding user response:
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.
CodePudding user response:
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())
console.log("data",data)
list = JSON.parse(data)
console.log("list",list)
}
init()