Reputation: 590
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:
VM22305 about:srcdoc:8 Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
Thanks for your help!
Upvotes: 2
Views: 4617
Reputation: 2066
If you want a chain of thens, you need to return a promise to the next one, like this:
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});
Upvotes: 2
Reputation: 10254
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.
Upvotes: 4