I got this error :
Cannot read properties of undefined (reading ‘forEach’)
if(response.Response) {
$('#list').html('');
response.Search.forEach(function(movie) {
var movieContent;
if(movie.Poster === 'N/A') {
movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
} else {
movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
}
$('#list').append(movieContent).hide().fadeIn();
});
}
});
The error comes when I put less than 3 letters in my search input and the output is
{Response: ‘False’, Error: ‘Too many results.’}
otherwise, from 3 letters the response is correct
{Search: Array(2), totalResults: ‘2’, Response: ‘True’}
I understand that this is because there is no Array in the response but how can I prevent this error?
2
Answers
You could simply check if the response.Response is not False instead of checking if a response exist.
Basically
You could also check if the Array is empty or undefined like @DBS pointed out.
His comment with the ? is also very useful. There are many ways
Read more:
How to check if an array is empty or exists?
From your API response you provided, if there is an error the
Response
property will equalFalse
asstring
.So in your
if
condition check if not equal to ‘Fales’.