JavaScript Create a Reusable Fetch Function

Paul Brubaker
Paul Brubaker
14,253 Points

Here is my solution that provides all breeds with their sub-breeds as options.

const select = document.getElementById('breeds');
const card = document.querySelector('.card'); 
const form = document.querySelector('form');

// ------------------------------------------
//  FETCH FUNCTIONS
// ------------------------------------------

function fetchData(url) {
  return fetch(url)
          .then(res => res.json())
}

fetchData('https://dog.ceo/api/breeds/image/random')
  .then(data => generateImage(data.message))

fetchData('https://dog.ceo/api/breeds/list/all')
  .then(data => generateOptions(data.message))

// ------------------------------------------
//  HELPER FUNCTIONS
// ------------------------------------------

function generateImage(data) {
    const html = `
      <img src='${data}' alt="DOG">
      <p>Click to view images of ${select.value}s</p>
    `;
      card.innerHTML = html;
}

function getReadableBreed(breed) {
  if (breed.includes('/')) {
      readableBreed = `${breed.split('/')[1]} ${breed.split('/')[0]}`;
    } else {
      readableBreed = breed;
    }
  return readableBreed;
}

function generateOptions(data) {
  let breedsList = [];
  let html = '';
  Object.keys(data).forEach(breed => {
    if (data[breed].length === 0) {
      breedsList.push(breed);
    } else {
    data[breed].forEach(subBreed => {
      breedsList.push(`${breed}/${subBreed}`)
    })
    }
  })
  breedsList.forEach(breed => {
    const readableBreed = getReadableBreed(breed);
    html += `<option value=${breed}>${readableBreed}</option>`
  });
  select.innerHTML = html;
}

function fetchBreedImage() {
  const breed = select.value;
  const img = card.querySelector('img');
  const p = card.querySelector('p');
  const readableBreed = getReadableBreed(breed);

  fetchData(`https://dog.ceo/api/breed/${breed}/images/random`)
    .then(data => {
      img.src = data.message;
      img.alt = breed;
      p.textContent = `Click to view more ${readableBreed}s`;
    })
}
// ------------------------------------------
//  EVENT LISTENERS
// ------------------------------------------

select.addEventListener('change', fetchBreedImage);
card.addEventListener('click', fetchBreedImage);