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();
}