skip to Main Content

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


  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?

    Login or Signup to reply.
  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(); 
          });
        }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search