I'm trying to add an autocomplete to a simple form input (movie title) based on the API "the movie DB" (https://developers.themoviedb.org/3/search/search-movies).
const findMovies = (wordToMatch) => {
const url = `https://api.themoviedb.org/3/search/movie?api_key=263e31d1ad0c4defa8822787e614e716&language=en-US&query=${wordToMatch}&page=1&include_adult=false`
const movies = [];
fetch(url)
.then(blob => blob.json())
.then(data => data.results.forEach(result => movies.push(result.original_title)));
return movies;
}
function displayMovies() {
const moviesArray = findMovies(this.value);
const html = moviesArray.map(movie => {
return `
<li>
<span class="movie">${movieName}</span>
</li>
`;
});
suggestions.innerHTML = html;
}
const titleInput = document.querySelector("#memory_cultural_good_attributes_title");
const suggestions = document.querySelector('.suggestions');
if (titleInput) {
titleInput.addEventListener("keyup", displayMovies);
}
<%= movie_form.input :title %>
<ul class="suggestions">
</ul>
The findMovies function works well and returns an array of the movies according to the input of the user. The problems seems to be when I iterate over this array (moviesArray) in the displayMovies function it is not giving the expected results.
Indeed, when I log the result of html in my console, it's empty. It seems that the map didn't work on the moviesArray. I was wondering if maybe moviesArray would not be an array, but if I print the array in console like this console.log(Array.isArray(moviesArray)) then, I get "true" as a response.
Hope my question is clear (this is my first one here), don't hesitate to ask me for additional details.
Many thanks !