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.
CodePudding user response:
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.
CodePudding user response:
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 } );
}
choice
is state variable, so directly accessible by its name. No need to link to your component props with props.choicesetChoice 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.