DEV Community

loading...

Fetch Exercise (Github users)

Manuel Alonge
Originally published at github.com ・1 min read

Hello, I am trying to create a table with JSON calls given by the usernames of Github users. Github Repo.

I was able to do it for one line (it shows username, avatar and bio), but I am struggling with doing it on multiple lines. I've tried by myself for a while. I think I am very close to the solution but still I was unable to populate each row with the elements. Can anyone help with an input? Many thanks.

Code:

//Step1
var users = [];

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

  users.push(prompt('Enter your Github user name'));

}

for (var user of users) {
  fetch(`https://api.github.com/users/${user}`).then((response) => {

    return response.json();

  }).then((responseJson) => {

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

  });
}

//Step2
function injectInfo(responseJson) {

  //How I am trying to populate the other lines
  var table = document.getElementById('myTable');
  var row = table.insertRow(2);

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

    var cell = row.insertCell(c);

  };

  //How to populate one line
  document.querySelector('.username__cell').innerHTML = responseJson.login;
  document.querySelector('.avatar__cell').innerHTML = responseJson.avatar_url;
  document.querySelector('.bio__cell').innerHTML = responseJson.bio;

  var avatar = document.createElement('img');
  var src = document.querySelector('.avatar__cell');
  avatar.src = responseJson.avatar_url;
  src.appendChild(avatar);

}



Enter fullscreen mode Exit fullscreen mode

Discussion (4)

Collapse
savagepixie profile image
SavagePixie

The problem is that you're always selecting the same cells to update the innerHTML. There is only one cell in your table with the class username__cell and so on. What you need to do in step 2 is dynamically generate something to identify the cells that you create. A unique ID would work. You could try something like this:

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

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

  //How to populate one line
  document.querySelector(`#${responseJson.login}_0`).innerHTML = responseJson.login;
  document.querySelector(`#${responseJson.login}_1`).innerHTML = responseJson.avatar_url;
  document.querySelector(`#${responseJson.login}_2`).innerHTML = responseJson.bio;

  var avatar = document.createElement('img');
  var src = document.querySelector(`#${responseJson.login}_1`);
  avatar.src = responseJson.avatar_url;
  src.appendChild(avatar);
Collapse
manuelalonge profile image
Manuel Alonge Author

It works. Now I should only refactor it in order to do it dinamically (i.e. if I had more than only two users). Thanks @savagepixie .

Collapse
savagepixie profile image
SavagePixie

You're welcome^ I'm glad I could help

Collapse
manuelalonge profile image
Manuel Alonge Author