Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda