Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda