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

205
Vistas
how do i add a key-value pair to an object in state of functional components

i've seen some stuff about computed property names for class components, is there a similar solution for functional components?

i have an initial state of {}.

const [choice, setChoice] = useState({})

as a button clicks, i'd like to add a new k:v to it dynamically.

onClick={()=>{ 
setChoice( props.choice[Key]=[Val] );
}

this doesn't seem to work...

and i'm hoping to add to the choice variable, like so: {"key":"val","key1":"val1",etc..)

i've also tried this:

class Choice {
    constructor(key, value){
      this.key = key,
      this.value = value
    }
  }

but not sure how to adjust the onClick for it.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To add to the current state a new key value pair:

onClick={() => {
    setChoice( currentState => {
        return {...currentState, Key:Val}
        }
}}

The handler on set state has this overload that let's you use the previous state and add to it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

the problem comes from your accessor for choice in the onClick function. The good syntax should be (because choice is accessible directly as a variable in your component)

onClick={()=>{ 
setChoice( { ...choice, key:val } ); 
}
  1. choice is state variable, so directly accessible by its name. No need to link to your component props with props.choice

  2. setChoice should take as an argument the original variable, plus the new key/value pair. Thus the destructuring of ...choice and the added member variable key:value.

Edit: if you want your updates to be more sound with the React way, you should use the callback syntax. Finally you would have

setChoice(choice => { return {...choice, key:val}})

This preventing some noodling, coming from the asynchronous nature of state updates in React.

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