0

I rewrote my code using fetch instead of using callbacks, now the page is letting me loop through the API data. Even though I can see the data being fetched from the API in the console, when I use console.log.

Now I am getting this error message

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
    at scripting.js:30:40
runCode.addEventListener("click", ()=>{
    
    fetch(theUrl)
        .then(response=>{response.json()})
        .then((data)=>{
            for(let i=0;i<data.length; i++){
                generateHTML(data[i]);
            }
        })
    });
VLAZ
  • 26,331
  • 9
  • 49
  • 67
myko
  • 65
  • 5
  • `response.json()` returns another promise. – Evert Apr 09 '23 at 05:33
  • I am now getting this error message , I changed to the code to the code above "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length') at scripting.js:30:40" – myko Apr 09 '23 at 06:06

1 Answers1

1

response.json() returns a Promise, which you need to wait for.

You can do this by chaining Promise#then.

fetch(theUrl).then(response => response.json()).then(data => {
    // now use data
});

You could also use await in an async function.

runCode.addEventListener("click", async e => {
    let data = await (await fetch(theUrl)).json();
    // use data here
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • I changed the code but now I am getting this error message for the for loop "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length') at scripting.js:30:40" – myko Apr 09 '23 at 06:06
  • I get "undefined" – myko Apr 09 '23 at 06:41
  • @myko You made a typo in copying over the code in my answer. It must be `.then(response => response.json())` **without** extra curly braces (i.e. remove the `{}`). – Unmitigated Apr 09 '23 at 06:42
  • aha that worked after I fixed that, thank you so much – myko Apr 09 '23 at 06:50