0

When I'm running the below, the first time it runs I get "Uncaught TypeError: Cannot read property '0' of undefined" but it runs fine the second+ times. Why is this and how can I avoid this.

at HTMLButtonElement.newtexttotype

function newtexttotype () {

fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data});
console.log(newtexthere[0].description);

}

1 Answers1

1

Simply put, fetching the data from that URL is an asynchronous operation - it takes some time to complete.

The first time you run the code, by the time you're doing your console.log, the data hasn't yet arrived and your array hasn't been populated yet. By the time you click to run it a second time, the request has completed and the information is there.

How to fix it?

I don't know if you're aware, but your fetch call is returning a promise, which is a way to deal with asynchronous operations. A promise exposes a .then method where you can put code that will run once your promise finishes doing its job succesfully.

So, you should move your console.log inside a .then, to make sure that by the time you're logging, the information you need is already there.

fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data})
.then(()=> console.log(newtexthere[0].description));
Ruben Serrate
  • 2,724
  • 1
  • 17
  • 21
  • In this specific case, I think the OP just needs to move the console log inside the second `then()` (`.then(data => {newtexthere = data.data; console.log(newtexthere[0].description)})`); there should be no need to create a third `then()`, as the `newtexthere = data.data;` assignment operation is not an asyncronous one. – secan Sep 29 '20 at 11:55
  • 1
    Yeah just did it like that for clarity, but you're right, no need. – Ruben Serrate Sep 29 '20 at 13:08