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

170
Views
React useState - update all object values to true

I have defined an object as follows in a file:

export const items = {
  first: false,
  second: false,
  third: false
}

I'm using it in a component as follows:

import { items } from 'file';
const [elements, setElements] = useState(items);

I have a method which gets called when a button is clicked - the method should change the all the values in elements to true

Using the following changes the values but it does not trigger a re-render of the component (which is what I need)

Object.keys(elements).forEach(element => elements[element] = true);

How can I use setElements to update all the values in elements?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem you are facing is that you are mutating the state object, which means that at the end, prevState === nextState and React bails out of rendering. An option is to use a new object and copy the props like this, using the same combo of Object.keys and forEach but adding an extra step:

setState(prevState => {
  const nextState = {}
  Object.keys(prevState).forEach(key => {
    nextState[key] = true
  })
  return nextState
})
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!