DEV Community

loading...

Lorem Picsum Fetch Exercise

Manuel Alonge
・1 min read

Hi,

I am trying to show on my HTML page some pictures from Lorem Picsum API's. So far I was able to fetch an array of 30 pictures but I am unable to show them on the page through the "createElement" of Javascript. I think the link is probably wrong, I should try with https://picsum.photos/id/1 but then I get an error. Here the repo: https://github.com/manuelalonge/github-users-fetch/tree/master/Es2

Current JS code below

//Step 1 - create an array of photos
var photos = [];



  fetch(`https://picsum.photos/v2/list`).then((response) => {

    return response.json();

  }).then((responseJson) => {

    //injectInfo(responseJson);
    console.log(responseJson);

  });




//Step 2 - add photos from picsum api via javascript
function injectInfo(responseJson) {

  var table = document.getElementById('myTable');
  var row = table.insertRow(1);

  for (var c = 0; c < 2; c++) {

    var cell = row.insertCell(c);
    cell.id = `${responseJson.author}_${c}`;

  }

  document.querySelector(`#${responseJson.author}_0`).innerHTML = responseJson.download_url;
  var photo = document.createElement('img');
  var src = document.querySelector(`#${responseJson.author}_1`);
  photo.src = responseJson.download_url;
  src.appendChild(photo);

}
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
sfiquet profile image
Sylvie Fiquet

If you use the developer tools, you can see that your table elements are created properly but responseJson.author is undefined:

<td id="undefined_0">undefined</td>
<td id="undefined_1"><img src="undefined"></td>

responseJson is an array as shown in the console.log. But all the code in injectInfo treats it like an object. You need to use the object's index in the array, e.g. responseJson[0].author, responseJson[0].download_url, etc...