How to properly fetch iTunes API?

387 views Asked by At

Basically, I need to fetch and use promises in order to do this exercise. However, I cannot get the results I want. The goal is to fetch data from the iTunes API and encode the response as JSON, passing it into my helper function.

//What I've tried
const URL_TEMPLATE = "https://itunes.apple.com/search?entity=song&limit=25&term={searchTerm}";

function fetchTrackList(param) {
  let url = URL_TEMPLATE.replace('{searchTerm}', param);
  let promise = fetch(url);
  promise.then(function(res) {
    return res.json();
  })
  .then(function(res) {
    renderSearchResults(res);
  });
}
//My render methods
function renderTrack(track) {
  let newDiv = $('<img>');
  newDiv.attr({src: track.artworkUrl100, alt: track.trackName, title: track.trackName});
  $('#records').append(newDiv);
}

function renderSearchResults(obj) {
  $('#records').empty();
  obj.results.forEach(result => {
    renderTrack(result);
  })
}

//Now it's the time to practice using `fetch()`! First, modify the `index.html`
//file to load the polyfills for _BOTH_ the fetch() function and Promises, so
//that your example will work on Internet Explorer.
//Use version 2.0.4 of the `fetch` polyfill.


//Define a function `fetchTrackList()` that takes in a "search term" string as a
//parameter and uses the `fetch()` function to downloads a list of tracks from 
//the iTunes Search API. You can use the below `URL_TEMPLATE` string for the URL,
//replacing `"{searchTerm}"` with the passed in search term (no {})
//Send the AJAX request, _then_ encode the response as JSON once it is received, 
//and _then_ should call you `renderSearchResults() function and pass it the 
//encoded data.
//
//IMPORTANT: Your `fetchTrackList()` method must also _return_ the Promise
//returned by the end of the `.then()` chain! This is so the method itself will
//be asynchronous, and can be further chained and utilized (e.g., by the tester).
//
//You can test this function by calling the method and passing it the name of 
//your favorite band (you CANNOT test it with the search button yet!)
const URL_TEMPLATE = "https://itunes.apple.com/search?entity=song&limit=25&term={searchTerm}";

I expect tracks to actually render, however; nothing renders. I can only assume I've done something wrong, but do not know where to go about it.

0

There are 0 answers