TypeError: Cannot read properties of undefined in javascript

Dung Do Tien May 24 2022 471

Hi you guys, I am a newbie in javascript & ES6. I have a task that needs to get data from an API and raw it to HTML. I use fetch() method to help call API. I code as below:

fetch('https://hn.algolia.com/api/v1/search?take=25&query=.net', {
  method: 'GET',
})
.then(response => response.json())
.then(result => {
  
  for(let i = 0;i < 25; i++){
      console.log(result.hits[i].title);
  }
})
.catch(error => {
  console.error(error);
});

But when  I run the code above I got an error TypeError: Cannot read properties of undefined (reading 'title').

TypeError: Cannot read properties of undefined (reading 'title')
    at <anonymous>:13:32
n.<computed>.n.<computed> @ (index):15
(anonymous) @ script.js:13
Promise.catch (async)
(anonymous) @ script.js:13
hn @ (index):18
playcodeUpdateWindow @ (index):27
(anonymous) @ (index):27
(anonymous) @ (index):14
e._handleSignal @ (index):14
e.dispatch @ (index):14
port.onmessage @ (index):17

How can I prevent reading data undefined?

Thanks for any suggestions.

Have 1 answer(s) found.
  • i

    ihya mohamed May 24 2022

    The solution for your issue is needs to check null before loop data. You take 25 records but API did not return the full 25 records. You can do as below:

    Note 1: Check the length of the array before you loop.

    Note 2: Only loop from 0 to the total item of an array.

    fetch('https://hn.algolia.com/api/v1/search?query=.net', {
      method: 'GET',
    })
    .then(response => response.json())
    .then(result => {
       if(result.hits.length > 0){ // Check length of array before loop
        for(let i = 0;i < result.hits.length; i++){ // only loop from 0 to total item of array.
            console.log(result.hits[i].title);
        }
       }
    })
    .catch(error => {
      console.error(error);
    });

    I hope this answer will useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close