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

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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