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

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

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 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