Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
How can I retrieve and loop through data retrieved from a fetch request?

I am using an open-source api to retrieve breweries when people search by city name. I can console. log the promise returned but when I try to loop and console.log the data it tells me undefined.

const searchBtn = document.getElementById('beer-search-button');

const getBeerData = (cityName) => {
    const beerApi = `https://api.openbrewerydb.org/breweries?by_city=${cityName}`;
    encodeURI(beerApi);
    fetch(beerApi)
    .then(res => {
        if(res.ok) {
            console.log(res.json());
            for(let b in res) {
                console.log(b.name);
            }
        } else {
            console.log('Error!');
        }
    });
}

searchBtn.addEventListener('click', function(e) {
    e.preventDefault;
    let searchQuery = document.getElementById('city-input').value;
    
    getBeerData(searchQuery);
});
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You need to loop over the result of res.json(). You do this with another .then().

And calling encodeURI() without using the result has no effect. You should be calling encodeURIComponent() on the city name, and using that in the URI.

const getBeerData = (cityName) => {
  const beerApi = `https://api.openbrewerydb.org/breweries?by_city=${encodeURIComponent(cityName)}`;
  fetch(beerApi)
    .then(res => {
      if (res.ok) {
        return res.json()
      } else {
        throw "Error";
      }
    }).then(res => res.forEach(b => console.log(b.name)));
}

about 4 years ago · Juan Pablo Isaza Report

0

res.json() also returns a Promise which you need to await either using then() or using await which is certainly my preferred option.

Please note that there is no need to URL encode the whole string as the API's URL is already encoded correctly, so you just need to URI encode the city name. Another thing you should probably do, is wait for the DOM to be loaded using DOMContentLoaded event before assigning event listeners as otherwise problems could occur because the DOM element might not yet be present.

const getBeerData = async (cityName) => {
  const beerApi = `https://api.openbrewerydb.org/breweries?by_city=${encodeURIComponent(cityName)}`;
  const res = await fetch(beerApi);
  if (res.ok) {
    const breweries = await res.json();
    breweries.forEach(brewery => console.log(brewery));
  } else {
    console.log("Error!");
  }
};

window.addEventListener("DOMContentLoaded", event => {
  const searchBtn = document.getElementById("beer-search-button");

  searchBtn.addEventListener("click", async function (e) {
    e.preventDefault;
    let searchQuery = document.getElementById("city-input").value;
  
    await getBeerData(searchQuery);
  });
})
<input type="text" id="city-input" name="city-input">
<button id="beer-search-button">Search for breweries!</button>

about 4 years ago · Juan Pablo Isaza Report

0

You've logged the promise but you haven't parsed that JSON. You can't loop over an array if it doesn't exist. And, because it's an array you should be using a for/of loop for (const b of data)....

Here's a shortened version.

// Get the data
fetch(beerApi)

  // Parse the data
  .then(res => res.json())

  // Loop over the data
  .then(data => {
    for (const b of data) {
      console.log(b.name);
    }

  });

});

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!