1

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?

Mathieu
  • 797
  • 2
  • 6
  • 24
  • Check whether `Search` exists before accessing it. Either with an `if`, or [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) `response.Search?.forEach(...)` – DBS Feb 23 '23 at 10:59

2 Answers2

2

From your API response you provided, if there is an error the Response property will equal False as string.

So in your if condition check if not equal to 'Fales'.

if(response.Response !== 'False') {
      $('#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(); 
      });
    }
  });
Mina
  • 14,386
  • 3
  • 13
  • 26
  • It would be safer to check the valid array *does* exist, rather than assuming the only possible fail state is the string "False" (Though that's completely valid given the details provided in the question) – DBS Feb 23 '23 at 11:03
  • @DBS, Yes this can be an extra check. – Mina Feb 23 '23 at 11:05
  • @DBS, but sometimes, through error is good enough to know where is the issue, let's say that the API by wrong returns `Response` equal to 'True' but doesn't return `Search` property, if we check the array validity before showing the data, this will lead to not throwing error and no data will be shown and the developer and user will expect that no search results for his input but the issue in the PI not in his `input`, I wish you understand my point. – Mina Feb 23 '23 at 11:17
1

You could simply check if the response.Response is not False instead of checking if a response exist.

Basically

if(response.Response !== 'False')

You could also check if the Array is empty or undefined like @DBS pointed out.

if (typeof response.Search !== 'undefined' && response.Search > 0)

His comment with the ? is also very useful. There are many ways

Read more:

How to check if an array is empty or exists?

SickerDude43
  • 168
  • 8