0

I am trying to use the variable 'myResult' to return specific JSON data. I believe I may have written the 'myResult' variable wrong and I am not querying for the correct data. The path for '[1].show.score'is correct and I will add in screenshots of the JSON data I am trying to call. When I call for this data, I get returned to me this error:

[![My error][2]][2]

Here is the result of 'url'

[![The returned JSON data from the variable 'url'][1]][1]

Here is my code:

document.querySelector('.myButton').addEventListener('click', function(){
  var query = document.getElementById('main').value;
  var url = fetch("http://api.tvmaze.com/search/shows?q="+query)
  .then(response => response.json())
  .then(data => console.log(data));
  var myResult = url[1].show.score;
  console.log(myResult);
})```


  [1]: https://i.stack.imgur.com/lTn8V.png
  [2]: https://i.stack.imgur.com/kS7gB.png
Marvin
  • 65
  • 1
  • 8
  • 3
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Reyno Sep 03 '20 at 11:26

1 Answers1

0

You cannot access the data from url the way you are trying to access it with url[1].show.score because url is a promise that you can call .then() and .catch() on, which you already do in order to receive the data.

If you want myResult to use the specific data, you need to use it within the .then() callback

So you may have something like this in the end:

document.querySelector('.myButton').addEventListener('click', function(){
  var query = document.getElementById('main').value;
  fetch("http://api.tvmaze.com/search/shows?q="+query)
  .then(response => response.json())
  .then(data => {
    console.log(data));
    var myResult = data[1].show.score;
    console.log(myResult);
  }
})
ezrag26
  • 28
  • 5