Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!