0

I'm fairly new to reactjs and javascript, so I'm not sure of the right syntax.

I want to use the spread operator to update an object but instead of hardcoding the field name I want it to be a variable, but it reads it as a field name instead of taking the variable value as the field name.

For example, This is my variable:

let [obj, setObj] = useState({'title': '', 'body': ''})

I update it like this:

const onChangeCallBack(field, value){
   if(field === 'body'){
       setObj(obj => ({...obj, 'body': value}))
   }else if(field === 'title'){
       setObj(obj => ({...obj, 'title': value}))
   }
}

I want to update something like this instead:

const onChangeCallBack(field, value){
   setObj(obj => ({...obj, field: value})) // This doesn't work
   setObj(obj => ({...obj, {field}: value})) // This doesn't work either
}

So is there a way to specify that the field is a variable to take it's value as the variable name?

Etch
  • 462
  • 3
  • 12

2 Answers2

3
setObj(obj => ({...obj, [field]: value}))

Use square brackets to use dynamic keys.

Jack
  • 788
  • 3
  • 13
1

You need to wrap dynamic keys with square braquets like so:

{ [myDynamicKey]: value }

More on the subject here: Creating object with dynamic keys

Manny Alvarado
  • 1,135
  • 9
  • 14