Search code examples
javascriptherokufetch-api

Rendering API results


I'm trying to render the "excuse" results from the following API. 'https://excuser.herokuapp.com/v1/excuse' I've followed several tutorials such as this (https://www.youtube.com/watch?v=uxf0--uiX0I) I'm able to pull the data using a button/onclick, however, their methods always generate an "undefined" whenever I try to actually get to the property I need out of the results which is "excuse".

Can you please let me know how to update the code below to pull in the "excuse" results? (It's okay if you're fetch/get request format is different. This is just the last attempt I tried. However, please non-React/Axios. I would like to use vanilla JavaScript.

async function getApi() {
const api_url = 'https://excuser.herokuapp.com/v1/excuse'
const response = await fetch (api_url);
const data = await response.json();
const {excuse} = data;
console.log(excuse);
} 

Solution

  • As I see excuse inside an array so you should do data[0] instead of data

    async function getApi() {
    const api_url = 'https://excuser.herokuapp.com/v1/excuse'
    const response = await fetch (api_url);
    const data = await response.json();
    console.log(data)
    const {excuse} = data[0];
    console.log(excuse);
    } 
    
    getApi();