Search code examples
javascriptasync-awaitfetch

How to get fetched data to show on HTML


I am going through the Coding Train video and trying my own take on it by fetching data from the Poemist API. I can get the title of the poem from the API to show up in the console; however, I can't get it to display on the HTML (it just shows undefined). Anyone know what I might be doing wrong here? Below is my code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Fetch a poem</title>
  </head>
  <body>
    <h1>Fetch a Poem</h1>
    <p id="poem">title</p>
    <script>
      console.log('about to fetch a poem');
      catchPoem()
        .then(poem => {
          document.getElementById('poem').innerText = poem;
          console.log('yay');
        })
        .catch(error => {
          console.log('error!');
          console.error(error);
        });

      async function catchPoem() {
        const response = await fetch('https://www.poemist.com/api/v1/randompoems');
        let json = await response.json();
        let title = json[0].title
        console.log(title);
      }
    </script>
  </body>
</html>


Solution

  • async function catchPoem() {
        const response = await fetch('https://www.poemist.com/api/v1/randompoems');
        let json = await response.json();
        let title = json[0].title
        // console.log(title);
        return title;
    }