Search code examples
javascripthtmlresponsefetch-api

Display a response from a Fetch with HTML?


My goal is to display some data on a webpage that I have obtained with a Fetch using HTML.

My Fetch (which works) looks like this

<script>
  let response = fetch(
    "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
  )
    .then((response) => response.json())
    .then((response) => console.log(response.events[0].title));
</script> 

The code works and logs a response to the console as I've requested. Now, I'd like to show some of the response on my webpage.

My attempts have looked something like this

<center><h2 id="response"></h2></center>    
<script>
      let response = fetch(
        "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
      )
        .then((response) => response.json())
        .then((response) => console.log(response.events[0].title))
        .then((response) => {
          document.getElementById("response").innerHTML = response.events[0].title;
        });
    </script>

Context and details:

  • I've done some mobile dev, but I'm a noob with even basic HTML/JS interaction on web so there are some holes in my knowledge here
  • I'll be implementing this code injection as a code block on a Squarespace (Adirondack template, Adirondack family) but I don't think the Squarespace context should matter (the Fetch works just fine, and the code injection has been displaying other things just fine)
  • Error from my attempt: VM22305 about:srcdoc:8 Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
  • I'm not committed to any particular way of displaying, I'm just trying to get the ball rolling by seeing something on the page

Thanks for your help!


Solution

  • Your second then is console logging and returning nothing (console.log returns undefined), so in the next then statement the response is undefined.

    Change your code to:

    <center><h2 id="response"></h2></center>    
    <script>
          let response = fetch(
            "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
          )
            .then((response) => response.json())
            .then((response) => {
              console.log(response.events[0].title);
              return response;
            })
            .then((response) => {
              document.getElementById("response").innerHTML = response.events[0].title;
            });
    </script>
    

    And it should work.