Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access image property from array of objects and display randomly when button is clicked

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading