Jump to content

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

Recommended Posts


In the following example I'm using fetch.all to combine two different API requests.

fetch.all and Handlebars.js

The unordered list, which is created by using Handlebars.js is showing all staffs from the second request.

Now my question:

How can I add the result of the first request to the same unordered list?

Share this post

Link to post
Share on other sites

I managed to fix it as follow:


  <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>
	    <!-- 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>


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;
  firstAPI = data[0];
	  secondAPI = data[1];
	  combinedData = {...firstAPI, ...secondAPI};
  // 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.

Share this post

Link to post
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