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

119
Vistas
Spread Operator Dynamic Properties Update

I have a state that looks like this:

state: {
    1: {show: false, description: 'one'},
    2: {show: false, description: 'two'},
    3: {show: true, description: 'three'}
   }

Depending on a variable "id" that comes from the action, I have to update the state.

Something like this:

var returnedState = {...state, [id].show : ![id].show}

How can I do this?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

{...state,
 [id]: {
  show: !state[id].show 
 }
}

that will copy the original state and then toggle the show value for the specific key/id that came from the action.

Here is a working code pen http://codepen.io/finalfreq/pen/mRBjZV

over 4 years ago · Santiago Trujillo Denunciar

0

The previous answer was correct but just leaves the show property on the sub object, removing the other ones. To keep all properties and change the property you want you have to use:

 {...state, [id] : {...state[id], show: !state[id].show}}

Have to add ...state[id]

over 4 years ago · Santiago Trujillo Denunciar

0

this.setState(prevState => ({
...state,
state[id]: !prevState[id].show
}))

Here you have to take last state as prevState and then update the object with supplied key with opposite value of previous state's object.

over 4 years ago · Santiago Trujillo 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