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

123
Views
Async updating multiple properties on a state object using React useState() hook
const [obj, setObj] = useState{
  id1: false,
  id2: false,
...
})

const someFunc = async(id)=> {
  setObj({...obj, [id]: true})
  await longApiCall()
  setObj({...obj, [id]: false})
}

This function gets called a couple times (or more), and this should set both to true then both to false, but they complete at close to the same time. Because setting state is asynchronous, each set state only flips one to false because the second one overwrites it back to true.

What's the best way to ensure the state object always gets the correct updates? I know that I can use a ref or directly set the property on the obj without using the state setter, but I want to maintain the behavior that this state change causes a rerender.

// after calls are finished
obj = {
  id1: true,
  id2: false
}

//desired outcome
obj = {
  id1: false,
  id2: false
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use the function version of set state instead. React will pass you in the latest value of the state, and you can calculate the new state from that:

const someFunc = async(id)=> {
  setObj(prev => {
    return {...prev, [id]: true};
  });
  await longApiCall();
  setObj(prev => {
    return {...prev, [id]: false};
  });
}
about 4 years ago · Juan Pablo Isaza Report

0

This is the cleanest solution I could come up with.

const objMimic = useRef({})

const someFunc = async(id)=> {
  objMimic.current[id] = true
  setObj({...obj, [id]: true})
  await longApiCall()
  objMimic.current[id] = false
  setObj({...objMimic.current})
}
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!