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

Refactoring generates: app.js:10 Uncaught (in promise) TypeError: res.join is not a function at app.js:10 -

Refactoring to use fetchData generates the above issue:

Used different naming but I fail to find the issue. When taking out the refactoring and adding back the old then(response...) everything is fine.

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.join());
}

fetchData("https://dog.ceo/api/breeds/list").then((data) =>
  generateListItems(data.message)
);

function generateListItems(data) {
  const items = data
    .map(
      (item) => `
      <option value='${item}'>${item}</option>
      `
    )
    .join("");
  select.innerHTML = items;
}

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

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

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

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

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

2 Answers

Blake Larson
Blake Larson
13,014 Points

You want to use the .json() function on the response object, which extracts the JSON body content from the response.

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

I missed the error, thanks a lot!