Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
210,095 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
210,095 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 !!!