dor_sam
dor_sam

Reputation: 95

How do I catch data from api after looping it to DOM

I've created a global variable named movieID and I have a function called generateSearch which gets data from API and then the displayResults function loops over the results and displays the data on DOM.

My goal is to insert an event listener which when you click on a specific title of movie (#more-details) the movieID variable will take the clicked movie's ID!

//GLOBAL VARIABLES
let resultArr = [];
let movieID;

//EVENT LISTENER
submitBtn.addEventListener('click', generateSearch)

//GENERATE SEARCH DATA
async function generateSearch() {
    resultArr = []

    const result = await fetch(`${baseURL}${search}${userInput.value}${apiKey}`)
    const data = await result.json();

    //push data in array
    data.Search.forEach(element => {
        resultArr.push(element)
    })
    console.log(resultArr)

    displayResults()
}

//DISPLAY ON UI
function displayResults() {
    clearUI()
    resultArr.forEach(movie => {
        const markup = `
       
        <div class="results">
            <img src="${movie.Poster}" alt="Movie Poster">
            <ul>
                <a href="#" id="more-details"><li>${movie.Title}</li></a>
                <li>${capitalizeFirstLetter(movie.Type)}</li>
                <li>${movie.Year}</li>
                <li>${movie.imdbID}</li>
            </ul>
            </div>
            
    `
        resultUI.insertAdjacentHTML('afterbegin', markup)

    })
    moviePage()
}

Upvotes: 0

Views: 43

Answers (3)

laruiss
laruiss

Reputation: 3816

You should try to avoid global variables. Here a solution with explanation in comments:

//EVENT LISTENER
submitBtn.addEventListener('click', event => generateSearch(event.target.value))
document.body.addEventListener('click', event => { // For every click...
    const clickedElement = event.target // Get the clicked element
    const movieId = clickedElement.dataset.movieId
    if (movieId) {
        // Do something with the movieId
        // ...
    }
})


//GENERATE SEARCH DATA
async function generateSearch(query) {
    const result = await fetch(`${baseURL}${search}${query}${apiKey}`)
    const data = await result.json();

    const nodes = getResultsAsArrayOfNodes(data.Search)

    //DISPLAY ON UI
    // searchResultElement should be a DOM node in which all the results will be appended
    searchResultElement.append(...nodes) // Append all the nodes (https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)
}

function getResultsAsArrayOfNodes(movies) {
    return movies.map(movie => { // For each movie...
        const node = document.createElement('div') // ...create a node..
        node.className = 'results'
        const markup = `
            <img src="${movie.Poster}" alt="Movie Poster">
            <ul>
                <!-- Create here an element with an id that contains the IMDB movie id -->
                <li><a href="#" data-movie-id="${movie.imdbID}">${movie.Title}</a></li>
                <li>${capitalizeFirstLetter(movie.Type)}</li>
                <li>${movie.Year}</li>
                <li>${movie.imdbID}</li>
            </ul>
        `
        node.innerHTML = markup // ...put the markup in the div.results node
        return node // return the node
    }) // Return the array of nodes
}

Upvotes: 2

Marc
Marc

Reputation: 1896

Set an click handler to a given function:

<a href="#" id="more-details" onclick="onTitleClicked('${movie.imdbID}')">

and

function onTitleClicked(id) { 
     console.info('do here what you want. id:', id);     
}

Upvotes: 2

Michal Szor&#225;d
Michal Szor&#225;d

Reputation: 215

Make sure your variable is really global.

window.movieID = null;

Then you should be able to do this.

<a href="#" id="more-details" onclick="window.movieID = ${movie.imdbID}">

Upvotes: 0

Related Questions