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

123
Visualizações
Sending multiple POST Req in a forEach loop React

In the code below I put a post REQ function inside a forEach loop and send a req for every selectedService entry that exists within that array. Then when the loop finished I fetch all the userServices and set that to my state.

  const handleAddServiceToUser = async () => {
    if (selectedServices === []) {
      setErr('Please Select A Service')
    } else {

      selectedServices.forEach(async (selectedService) => {
        await addNewUserService(userId, selectedService.id)
      })
      const res = await getUserServicesList(userId)
      setUserServices(res.data)

      handleClose()
      if (err !== '') {
        setErr('')
      }
      setSelectedServices([])
    }
  }

I have never seen or tried anything like this before (async forEach). The code does seem to be working when I test it in my client. I am assuming it is probably not a best practice to do something like this? Is this acceptable in terms of performance? And if not what is an alternative?

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