Jump to content

fetch.all and Handlebars.js - Combining the results of two API requests in one list


kayut

Recommended Posts

I managed to fix it as follow:

HTML

  <ul id="container" class="cf"></ul>
	
  <script id="ourTemplate" type="text/x-handlebars-template">
	    <!-- Data coming from staff array -->
    {{#each staff}}
      <li class='list-container'>
        <div class='img-container'><img src="{{ this.image_url }}"></div>
        <div class='name-container'>{{ this.name }}</div>
      </li>
    {{/each}}
	    <!-- Data coming from the results array -->
    {{#each results}}
    <li class='list-container results'>
      <div class='img-container'><img src="{{ this.picture.medium }}"></div>
      <div class='name-container'>{{ this.name.first }} {{ this.name.last }}</div>
    </li>
    {{/each}}
  </script>

JavaScript

const apiRequest1 = fetch('https://randomuser.me/api/?results=10').then(function(response){ 
  return response.json()
});
	const apiRequest2 = fetch('https://api.jikan.moe/anime/1/characters_staff').then(function(response){
  return response.json()
});
	let combinedData;
	Promise.all([apiRequest1,apiRequest2]).then(function(data){
  firstAPI = data[0];
  console.log(firstAPI);
	  secondAPI = data[1];
  console.log(secondAPI);
	  combinedData = {...firstAPI, ...secondAPI};
  console.log(combinedData);
	  createHtml(combinedData);
  // createHtml(combinedData.results);
  // return combinedData;
})
.catch(function(error) {
  console.log('Looks like there was a problem: \n', error);
});

// Function to generate the HTML
function createHtml(ourData) { // ourData is just a parameter and can be named anything
  let rawTemplate = document.querySelector("#ourTemplate").innerHTML;
  let compiledTemplate = Handlebars.compile(rawTemplate);
  let ourGeneratedHTML = compiledTemplate(ourData);
  
  let ourContainer = document.querySelector("#container");
  ourContainer.innerHTML = ourGeneratedHTML;
}

Of course I had to run handlebars.js #each twice, once for each Ajax response.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...