-1

I've created a search bar for the NASA API using fetch().

The images for the first search inquiry load and display, but it takes multiple triggers of the search button's event listener to display a new inquiry. It seems like the old response gets accessed before its updated in the localStorage, or something similar?

Here is the Codepen: https://codepen.io/ana-ana/pen/orgbjB

I've tried to use setTimeout on the searches.push(JSON.parse(localStorage.getItem('response'))); to prevent the issue. I've also tried triggering the execute function multiple times. I've also tried storing the json response with a different name in localStorage each time the function is run.

function clear(){
    document.getElementById('images').innerHTML='';
}
var searches = [];
function search(inquiry){
console.log(fetch(inquiry));
        fetch(inquiry)
                  .then(function(response) {
                    var status = response.status;
                    return response.json();
                  })
                  .then(function(jsonResponse) {
                    localStorage.setItem('response', JSON.stringify(jsonResponse));
                  });
searches.push(JSON.parse(localStorage.getItem('response')));
}
function display(){
    for(i = 0; i<searches[searches.length - 1].collection.items.length; i++){
        var img = document.createElement('img');
        img.src = searches[searches.length - 1].collection.items[i].links[0].href;
        document.getElementById('images').appendChild(img);
    }   
}


document.getElementById('btn').addEventListener('click', execute);

function execute(){
    clear();
    search(`https://images-api.nasa.gov/search?q=${document.getElementById('searchbar').value}`);
    console.log(searches[searches.length - 1]);
    display();
}
anacodes
  • 1
  • 2
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Jun 11 '19 at 19:46
  • check out https://codepen.io/anon/pen/GbgoEd – Thomas Jun 11 '19 at 20:06

1 Answers1

0

In your search function, you are pushing to your searches array outside of the promise, meaning that it is probably happening before the promise has had a chance to resolve

  • Edit: moving `display()` into the promise solved the issue!! thanks!! ........ Moving the `searches.push` inside the promise helped! The search array only updates once the new promise has resolved. the issue is, it still takes multiple search clicks to update the display! i've updated the codepen to reflect your response: https://codepen.io/ana-ana/pen/orgbjB – anacodes Jun 11 '19 at 19:56