I’m trying to access the image property from the array of objects from NASA API , so it can be displayed randomly when I click on a button
I want a different image to be shown whenever I click a button. The images are from an array of objects from NASA api.
document.querySelector('button').addEventListener('click', getFetch)
function getFetch() {
const url = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=1wCuyjoxfSrvsEbUpfWJvuBEMB5I0x79kXS0pfrg'
fetch(url)
.then(res => res.json()) // parse response as JSON
.then(data => {
console.log(data)
data.photos.forEach(element => {
document.querySelector('img').src = element.img_src
f
});
})
.catch(err => {
console.log(`error ${err}`)
});
}
>Solution :
I’d say that you are doing it the wrong way around – don’t fetch up to 1000 images on click, fetch them first and cycle through them on click.
const button = document.querySelector('button');
const img = document.querySelector('img');
const imgUrl = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=1wCuyjoxfSrvsEbUpfWJvuBEMB5I0x79kXS0pfrg'
const makeImgCycler = (images) => {
return () => {
const n = Math.floor(Math.random() * images.length);
return images[n];
};
};
const fetchImgs = (url) => {
return fetch(url).then(r => r.json());
};
fetchImgs(imgUrl).then(data => {
const nextImage = makeImgCycler(data.photos);
button.disabled = null;
button.addEventListener('click', () => {
img.src = nextImage().img_src;
});
});
<button disabled>Next</button>
<img alt="">
Hint
The "Next" button is initially disabled until the images are loaded.
EDIT
Made makeImgCycler/nextImage return a random image. Not checking if it returns the same random image on subsequent clicks, though.