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

248
Visualizações
React: how to wait for map function to complete before updating state?

I have an array of ids, stored in ids, that I'm mapping over an async function, asyncFunc. I want to store the result of the mapping into newArr and then update state via setState. Here's my code:

useEffect(() => {
    const newArr = [];
    ids.map((element) => {
      asyncFunc(variables).then((data) => {
        newArr.push({ layer: makeLayer(data) });
      });
    });
    setState([...layers, ...newArr]);
  }, [variables]);

My issue is that the state is updating before the mapping completes. How can I use .then() to update the state only when data from all the mappings were returned? Wrapping ids.map with Promise.all didn't work. In addition, the following returns an error:

useEffect(() => {
    const newArr = [];
    (ids.map((element) => {
      asyncFunc(variables).then((data) => {
        newArr.push({ layer: makeLayer(data) });
      });
    })).then(()=> {
       setState([...layers, ...newArr]);    
    })
  }, [variables]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Declare a async function to populate the array and return your array within a Promise.all. Something like this should work for what you're trying to accomplish:

useEffect(() => {
    const populateArray = async () => {
      const newArr = await Promise.all(ids.map(async element => {
        const data = await asyncFunc(variables)

        return { layer: makeLayer(data) }
      })

      setState([...layers, ...newArr]);
    }

    populateArray()
  }, [variables]);
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