0

I am using the results from one fetch to generate some elements for a div in my HTML. Within these fetched elements is a list of URLS I am using to fetch some additional elements. My goal is to merge data from both fetches into an HTML div. My current code is accessing the data, but not merging correctly in the final div.

I've attempted to rewrite the code into nested fetches and functions and the same issue persists.

var request = new XMLHttpRequest()

request.open('GET', 'https://statsapi.web.nhl.com/api/v1/teams/14?expand=team.roster', true)

var age =""
var height = ""
var weight = ""
var nationality = ""


request.onload = function () {
  var data = JSON.parse(this.response)
  var team=data.teams[0].roster.roster

  for (index = 0; index < team.length; ++index){
    var name = JSON.stringify(team[index].person.fullName).replace(/"/g,'');
    var position = JSON.stringify(team[index].position.name).replace(/"/g,'');
    var num = JSON.stringify(team[index].jerseyNumber).replace(/"/g,'');
    var div = document.createElement("div");
    var link = JSON.stringify(team[index].person.link).replace(/"/g,'');


    fetch('https://statsapi.web.nhl.com' + link)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            age = JSON.stringify(myJson.people[0].currentAge);
            height = JSON.stringify(myJson.people[0].height);
        weight = JSON.stringify(myJson.people[0].weight);
            nationality = JSON.stringify(myJson.people[0].nationality);
        });

      div.innerHTML='<a href="#" class="list-group-item" data-toggle="collapse" data-target="#sm" data-parent="#menu">' + name + ' <span class="label label-info">' + num + '</span></a>'
        div.innerHTML=div.innerHTML + '<div id="sm" class="sublinks collapse">'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + age + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + height + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + weight + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + nationality + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + position + ' </a> </div>'
    document.getElementById("main").appendChild(div);
  }
}


// Send request
request.send()

Create an element that contains data from both fetches.

2 Answers2

0

You can use Promise.all to achieve your functionality

fetch('url1').then(response1 => response1.json()).then(result =>{
// write you data extraction logic here

// do fetch call from fetched data

var fetch2 = fetch('url2').then(response2 => response2.json())
return Promise.all(Promise.resolve(result), fetch2)
}).then(allResult => {

// here you will have data from both the fetch call
})
0

Fetch returns promises and you can chain promises. Check this.

Try this solution.

fetch('https://statsapi.web.nhl.com/api/v1/teams/14?expand=team.roster')
.then(response => {
    return response.json().then(data => data.teams[0].roster.roster);
}).then(teams => {
      for(team of teams) {
         const {jerseyNumber, person:{fullName, link}, position:{name}} = team;

         fetch('https://statsapi.web.nhl.com' + link)
            .then(res => {
                return res.json().then(data => data.people[0]);
            }).then(people => {
               const {currentAge, height, weight, nationality} = people;

               // Rest of the code. Create div elements.. 
               console.log(`Age: ${currentAge}, Height: ${height}, Weight: ${weight}, Nationality: ${nationality}, Num: ${jerseyNumber}, Name: ${fullName}, Position: ${name}`);
            });
      }
});
Razana N.
  • 70
  • 5