Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda