Reputation: 23
I'm trying to use OMDb API, and I keep getting this error. Followed all the steps from this YT video and I can't find the answer. It worked before I changed the code to declare moviesection() function outside of the createMovieContainer() . Here is my code:
let movieSearchable = document.querySelector('.movies-searchable')
let buttonElement = document.querySelector('#search');
const url = " http://www.omdbapi.com/?i=tt3896198&apikey=45ddf1ee&s=";
const posterURL = "http://img.omdbapi.com/?apikey=45ddf1ee&";
const apiKey = "45ddf1ee";
function movieSection(movies) {
return movies.map((movie) => {
return `
<img src=${movie.Poster} data-movie-id=${movie.Title}/>
`
});
}
function createMovieContainer(movies) {
let movieElement = document.createElement('div');
movieElement.setAttribute('class', 'movie');
let movieTemplate = `<section class="section">
${movieSection(movies)}
</section>
<div class="content">
<p id="content-close">
X
</p>
</div>
`;
movieElement.innerHtml = movieTemplate;
return movieElement;
}
buttonElement.onclick = function(event) {
let value = form.value;
let newUrl = url + value;
event.preventDefault();
fetch(newUrl)
.then((res) => res.json())
.then((data) => {
let movies = data.results;
let movieBlock = createMovieContainer(movies);
movieSearchable.appendChild(movieBlock);
})
.catch((err) => {
console.log('Error: ', err);
})
}
Upvotes: 0
Views: 327
Reputation: 29062
The API that you mentioned returns a response like this:
{
"Search": [
{
"Title": "Hello, My Name Is Doris",
"Year": "2015",
"imdbID": "tt3766394",
"Type": "movie",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTg0NTM3MTI1MF5BMl5BanBnXkFtZTgwMTAzNTAzNzE@._V1_SX300.jpg"
},
...
],
"totalResults": "592",
"Response": "True"
}
So, the movies exist in a property Search
of the response object - not in results
.
Therefore, data.results
is undefined
. You then go on passing that undefined
as movies
argument into createMovieContainer
, and from there into movieSection
. Finally you call movies.map(...)
which is essentially undefined.map(...)
at that point, and because undefined
doesn't have properties, the computer cannot read the map
property of undefined
that you are attempting to use, hence the error.
The fix: Change data.results
to data.Search
.
A word of advice: Next time, use a debugger. See what the values of your variables are when the error happens - you'd have noticed that movies
is undefined
. Then trace back where those values came from - you'd have noticed that the undefined
came from data.results
, and you'd have seen the actual structure of data
and that the movies array is called Search
.
Upvotes: 2