Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda