0

I'me giving my first steps with fetching APIs and I'm definitely missing something.

I want to have a single function that accepts a query as a parameter and fetches data from the API:

const fetchImgs = (query) => {
  fetch(`http://www.splashbase.co/api/v1/images/search?query=${query}`)
    .then((response) => response.json())
    .then((data) => data.images)
    .catch((err) => {
      displayAlert(err)
    })
}

And then I want to do something with the data received. For instance on window load I want to populate a carousel with forest images or when I click a button I want to populate an album with beach images. Something like this:

window.onload = () => {
  const forestsArray = fetchImgs("forest")
  populateCarousel(forestsArray)
}

mainImgBtn.addEventListener("click", () => {
  const beachesArray = fetchImgs("beaches")
  populateAlbum(beachesArray)
})

I know I could fetch my images everytime I need them and inside the 2nd then I could call functions to populate stuff but I'm curious if there is any way (and if it actually makes sense) to make my fetchImgs() function reusable. Because the problem is that when I'm invoking my populate functions I still don't have access to the data from fetchImgs() and I cannot do fetchImgs().then(something) because fetchImgs() doesn't return a promise.

I am also aware that I could wrap my populate functions on a setTimeout but that's kinda dirty I think. Is there any better way?

Tiago Brandão
  • 207
  • 3
  • 12

0 Answers0