Search code examples
javascriptdom-eventsjavascript-objectsfetch-api

How to iterate using iterator over API object using JavaScript?


I want to iterate over a JSON object(array) through JavaScript iterator. I am not able to store the data fetched from the iterator function in a variable so that I can use the variable for DOM manipulation.

next.addEventListener('click',nextCV);
function nextCV(){
   const a =getCV().then(data=> 
    data.next().value)
    

}

function getCV(){
    
    
     return fetch(url).then(response=>{return response.json()
    }).then(data=>{
        
       
        return iteratorCV(data.results)
    })
    
}

function iteratorCV(data){
    console.log('inside iterator')
    let nextindex=0;
    return {
        next: function(){
            return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true};
        }
    };
}

Here I want to get the next array data stored to variable 'a' whenever a click event occurs. Please help.

P.S. I am still in the process of learning JavaScript.


Solution

  • You're calling getCV() which does repeat the request and create a new iterator every time you click the element. It sounds like what you actually want to do is

    const iteratorPromise = getCV();
    iteratorPromise.catch(console.error);
    next.addEventListener('click', function nextCV(e) {
      iteratorPromise.then(iterator => {
        const a = iterator.next().value;
        console.log(a); // or DOM manipulation
      });
    });
    

    or

    getCV().then(iterator => {
      next.addEventListener('click', function nextCV(e) {
        const a = iterator.next().value
        console.log(a); // or DOM manipulation
      });
    }).catch(console.error);