Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Create a Reusable Fetch Function

Rishi B
Rishi B
13,866 Points

why 'breed' variable is blank ?

I couldn't get the picture of dog that matches to selected option.

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/list')
     .then( data => generateOptions(data.message))

const breed = select.value;

fetchData(`https://dog.ceo/api/breed/${breed}/images/random`)
     .then( data => generateImage(data.message) )

// ------------------------------------------
//  HELPER FUNCTIONS
// ------------------------------------------
function generateOptions(data){
      const options = data.map( item => `
            <option value=${item}>${item}</option>
      `).join('');
      select.innerHTML = options;
}

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

2 Answers

Steven Parker
Steven Parker
231,269 Points

As the page first loads, no selection has been made yet so the value is empty. That's why the code in the video only loads a random image to start with.

Later in the lesson, event listeners will be added that will load the breed image after a selection is made by the user.

Rishi B
Rishi B
13,866 Points

couldn't set the image to match the first option in the Options of 'select' element??

const breed = select.options[0].value;

above line is not working...

Steven Parker
Steven Parker
231,269 Points

No, it's also a timing issue. The "fetch" operation is asynchronous, so the assignment happens before any options have been loaded.

To guarantee the sequence, you'd need to make the image fetch part of another "then" chained to the options fetch:

fetchData("https://dog.ceo/api/breeds/list")
  .then(data => generateOptions(data.message))
  .then( _=> fetchData(`https://dog.ceo/api/breed/${select.value}/images/random`)
             .then(data => generateImage(data.message))
  );
Rishi B
Rishi B
13,866 Points

Thank you so much !!!