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

143
Vistas
React, update state in a loop

I would like to update a state each time I receive a promise, in a loop. But my state only shows the last promise. I guess it's because, as the set state is asynchronous, it uses the Map available before the previous state updates. How can I achieve that without using a Promise.all?

const [dataList, setDataList] = useRef(new Map())

  useEffect(() => {
    ids.forEach(id => {
      getData(id).then(data => {
        if (data) {
          setDataList(dataList.set(id, data))
        }
      })
    })
  }, [ids])
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It is related to how react works. It wait for all setState calls on a specific state and pick the last one. If you wanna avoid this behaviour use an updater function that will take the previous state and return a new one. In your case like so :

const [dataList, setDataList] = useRef(new Map())

  useEffect(() => {
    ids.forEach(id => {
      getData(id).then(data => {
        if (data) {
          setDataList(dataList => {
           let newDataList = new Map(dataList);
           newDataList.set(id, data);
           return newDataList;
           })
        }
      })
    })
  }, [ids])
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think you can achieve it with async await this way:

useEffect(() => {
  ids.forEach(id => {
    async function fetchMyAPI() {
      const data = await getData(id);
      if (data) {
        setDataList(dataList.set(id, data))
      }
    }
    fetchMyAPI()
  })
}, [ids])
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