How to set an object key inside a state object in React Hooks

1.5k Views Asked by At

How can I update a react hooks state object that has a nested object containing objects with index keys?

Here is the default state object.

  const [form, setForm] = useState({
      name:'',
      price:'',
      effects:{
          0:{},
          1:{},
      }

  })

My goal is to update the first key in the effects object.
I have tried some code like this.

const variable = "Sleepy"
const variableObject = {[variable]:0} 
setForm({...form, ...{...form.effects, ...{0:{ variableObject }} }  })

This attempt places the object outside of the nested effects object like this.

{
  0:{"Sleepy":0},
  1:{},
  name:'',
  price:'',
  effects:{
    0:{},
    1:{},
  } 
}

Instead, the final object state should look like this.

{
  name:'',
  price:'',
  effects:{
    0:{"Sleepy":0},
    1:{},
  } 
}
2

There are 2 best solutions below

1
On BEST ANSWER

How about:

form.effects[0].Sleepy = 0;
setForm({...form});
0
On

The solution you are looking for is something like this,

            ...form,
            effects:{
                ...form.effects,
                0: {...variableObject}
            }
        })

the spread operator inverts the packing of the object to open it inside out. So opening a layer, we could access the key-value pairs directly. . Also, there is yet another approach that might help you in the long run.

    setForm((oldForm)=>{ 
        return oldForm.effects.0 = variableObject 
    })

Notice you can also use the shorthand notation to reduce the amount of code you can write. Here i included the return clause to clarify the working of setState with callback. Anyways, here is the shorthand notation. setForm((oldForm)=> oldForm.effects.0 = variableObject) . Have a nice day