0

Im trying to display the joke of the day using RapidAPI. It's printing "undefined" inside of the div. I tried pulling "setup" and "punchline", but it wouldn't work. I don't have that sytax displayed here, but I'm almost positive that's where I'm going wrong. Here is the JSON from the console:

body: Array(1)
0:
NSFW: false
approved: true
author: {name: 'unknown', id: null}
date: 1618108661
likes: []
punchline: "Like bro you were there wtf"
setup: "Dentist always dumb questions like “when’s the last time you flossed?”"
type: "question"

Here is the main.js file

const RAPIDAPI_KEY =
  import.meta.env.VITE_RAPIDAPI_KEY;
const JOKE_URL = 'https://dad-jokes.p.rapidapi.com/random/joke';
const JOKE_HOST = 'dad-jokes.p.rapidapi.com';

const getData = async (url, host) => {
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      accept: 'application/json',
      'x-rapidapi-key': RAPIDAPI_KEY,
      'x-rapidapi-host': host,
    },
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.json();
};

const runApiQueries = async () => {
  ////////  GET JOKE RESULTS  //////////

  const jokeData = await getData(JOKE_URL, JOKE_HOST);
  console.log(jokeData);

  ////////  UPDATE UI WITH DATA /////////////
  app.innerHTML += /*html*/ `
    <div
    class="max-w-2xl
    w-full
    bg-yellow-400
    border-2 border-gray-300
    shadow-lg
    p-6
    rounded-md
    tracking-wide
    "
    >
    <div class="flex items center mb-4">
    <img alt="avatar"
    class="w-20"
    src= "./img/donkey1.jpeg"
    />
    <div class= "leading-5 ml-6 sm">
    <h4 class="text-xl font-semibold">Dad Joke</h4>
    <h5 class="font-semibold text-purple-800">Jokes</h5>
    </div>
    </div>
    <div class="text-center">
    <q class="italic text-white text-lg"
    >${jokeData.value}</q
    >
    </div>
    </div>
    `;
}
runApiQueries();
Ahmad Awais
  • 33,440
  • 5
  • 74
  • 56
  • 2
    `getData()` is an asynchronous request... you can't log its value right after calling it because it hasn't resolved yet. You should look into using a Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – skyline3000 Oct 25 '21 at 00:28
  • 2
    @skyline3000 OP is calling `getData()` within an `async` function and using `await` so that part of their code is completely correct – Phil Oct 25 '21 at 00:31
  • There are more elements...I just did not post them here since it was the Joke API that was in question. I have two other APIs. – Chaz Carothers Oct 25 '21 at 00:34
  • It's difficult to make out data structure when you copy the text from your console but it certainly doesn't look like there's a `value` property. Could you please change it to `console.log(JSON.stringify(jokeData, null, 2))` and update your question with what it displays – Phil Oct 25 '21 at 00:35

0 Answers0