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

201
Visualizações
Switching from .then to async / await in React app (with fetch and forEach)

I wrote a function fetching data from the Hacker News API with fetch and .then methods. That worked, but I'd like to learn to use the async / await -method. For some reason, the latter fetch within forEach loop returns undefined. Any idea how to fix this?

Here's the original code:

  componentDidMount() {
    // Get the top 20 post ids
    fetch("https://hacker-news.firebaseio.com/v0/beststories.json")
      .then(res => res.json())
      .then(json => {
        let topIds = json.slice(0, 20)
        this.setState({
          topIds: topIds
        })
        return topIds
      })

      // Get the posts based on the ids
      .then(ids => {
        ids.forEach(id => {
          fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
            .then(res => res.json())
            .then(data => {
              let thisPost = data
              this.setState({
                topPosts: [...this.state.topPosts, thisPost]
              })
            })
        })
      })
  }

Here's the new version:

  async componentDidMount() {
    this.getIds()
  }

  // Get the ID's
  async getIds() {
    // Get the top 20 post ids
    const res = await fetch("https://hacker-news.firebaseio.com/v0/beststories.json")

    const json = await res.json()

    const topIds = await json.slice(0, 20)
    this.setState({
      topIds: topIds
    })

    this.getPosts()
  }

  // Get the posts
  async getPosts() {
    const posts = this.state.topIds.forEach(id => {
      fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
    })

    const thisPost = await posts.json() // Posts returnes as undefined

    this.setState({
      topPosts: [...this.state.topPosts, thisPost]
    })
  }

I have tried adding both asyncs and awaits to all around the forEach loop, but haven't got it working. I also tried to convert it to for of loop, but got the same (undefined) result.

Thanks a lot in advance!

Edited: resolved this, here's the working version:

  // Get the posts
  async getPosts() {
    for (const id of this.state.topIds) {
      const post = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)

      const thisPost = await post.json()
      this.setState({
        topPosts: [...this.state.topPosts, thisPost]
      })
    }
  }
about 4 years ago · Juan Pablo Isaza
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