1

So I'm trying to use vanilla JavaScript and do a fetch from iTunes' API to create a page that allows a user to type in an artist name and then compile a page with like 15 top results. I'm using the following for my fetch:

 function dataPull() {
  fetch("https://itunes.apple.com/search?term=")
  .then(function(response) {
      if (response.status !== 200) {
        console.log(response.status);
        return;
      }
      response.json().then(function(data){
        console.log(data);
        let returnResponse = document.createElement("div");
        let input2 = inputElement.value;
        for (let i=0; i<data.length; i++){
          if (inputElement===data[i].artistName){
            console.log(data[i].artistName);
            returnResponse.innerHTML = `
            <div class="box">
            <img src=${artWorkUrl30} alt="Album Image">
            <p><span>Artist Name:</span>${data[i].artistName}</p>
            <p><span>Track: </span>${data[i].trackName}</p>
            <p><span>Album Name: </span>${data[i].collectionName}</p>
            <p><span>Album Price: </span>${data[i].collectionPrice</p>
            </div>
            `;
            results.appendChild(returnResponse);
        }}
        console.log(data);
      });
    }
  )

The function is being called in a click event and I'm sure I can put everything from "let returnResponse" down to the append in another function. The issue I'm having is actually getting the API to show ANY results. At the moment if I type in Bruno Mars, Beethoven, or U2 it's not logging any data and it's giving me "Provisional Headers are Shown" when I check out the the Status Code.

Any thoughts on what I could do to make this better/work?

For full code: jsfiddle

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user8387535
  • 41
  • 10

2 Answers2

0

Typical fetch call will look like this.

fetch(`${url}`)
    .then(response => response.json())
    .then(json =>
      // do something with the json
    )

Modify your code and see if you can console.log() anything of note.

Christopher Messer
  • 2,040
  • 9
  • 13
  • 1
    There's nothing wrong with *not* getting the JSON body when response status is not 200. – Bergi Aug 15 '17 at 02:06
0

I would reccomend seperating your concerns. Making the dataPull function just get the results. That means you can use this code at other places without changing it.

Here the function returns the json object as a promise.

 function dataPull(search) {
  return fetch("https://itunes.apple.com/search?term="+search).then(res => res.json());
 }

No you can call the dataPull function and resolve the promise. You'll have the result and can do what you want with it.

 dataPull("test").then(res => {
   console.log(res.results);

   /*
   res.results.forEach(item => {
    div and span magic here
   })
   */
 })

Here's a link to a working JSFiddle. https://jsfiddle.net/14w36u4n/

Bergur
  • 3,962
  • 12
  • 20