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

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

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