bsmith
bsmith

Reputation: 103

Why am I getting undefined as an answer when fetching data from an API?

I learning how to use fetch API and I am trying to print a quote from the Simpsons API as practice. The problem is that keep getting undefined as an answer. Do you know why it is not just printing the quote?

let button    = document.querySelector('#button')
let quote      = document.querySelector('#quote')

function getInfoFetch(){

  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {

      quote.innerText = data.quote;

    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch)

Upvotes: 0

Views: 4847

Answers (3)

Dacre Denny
Dacre Denny

Reputation: 30370

The API's response appears to be an array, which means you'll need to need to access the quote data from say, the first item of the array response.

You can do that by making the following change to your code:

let button = document.querySelector('#button')
let quote = document.querySelector('#quote')

function getInfoFetch(){

  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {
    
      // Access first item of data "array" to retrieve and display quote
      quote.innerText = data[0].quote;

    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch)
<button id="button">Get quote</button>
<div id="quote"></div>

Upvotes: 2

Jason Yang
Jason Yang

Reputation: 16

The data of second .then is an array with a object inside. If you want to get quote in the object, you need to use data[0] to select the object.Then, use .quote to select the key quote in the object. And you can get the value you want.

let button = document.querySelector('#button');
let quote = document.querySelector('#quote');

function getInfoFetch(){
  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {
      console.log(data); 
      //this is an array with object(index = 0) inside [{...}]
      quote.innerText = data[0].quote;
    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch);

Upvotes: 0

MyTwoCents
MyTwoCents

Reputation: 7622

Data which you are parsing is of Array type

[{"quote":"I can't even say the word 'titmouse' without gigggling like a schoolgirl.","character":"Homer Simpson","image":"https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939","characterDirection":"Right"}]

So to read that you need to pass index as well

fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {

      quote.innerText = data[0].quote;

    })
    .catch(err => console.log(err));

Here is working fiddle

Upvotes: 0

Related Questions