0

The code below works fine and react re-render the child:

const [equip, setEquip] = useState({biAbt:[]});
   const handleSet = (name, value) => {
   setEquip({[name]: value});
}

But if i try set the state with an object there is no render:

const [equip, setEquip] = useState({biAbt:[]});
const handleSet = (name, value) => {
   let obj = equip;
   obj[name] = value;
   setEquip(obj);
}

What am I doing wrong? I need to add or update a property to the existing state object.

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • 1
    Try this ---> let obj = {...equip}; – Sarun UK Jun 25 '21 at 15:58
  • `let obj = equip;` is not doing what you think it is. In JavaScript objects and arrays are stored in variables by their references. Assigning it to a new variable simple assigns it the same reference. This means you're mutating the original state, and React does not think it needs to re-render. – Brian Thompson Jun 25 '21 at 15:58
  • Does this answer your question? [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Brian Thompson Jun 25 '21 at 16:01
  • Also see [why-cant-i-directly-modify-a-components-state-really](https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really) – Brian Thompson Jun 25 '21 at 16:20

1 Answers1

0

When you assign let obj = equip; obj has the same reference as the previous state, so react will not re-render, you can you it like this instead:

const handleSet = (name, value) => {
   setEquip(equip => ({...equip, [name]: value}));
}

by spreading into a new object, a new reference will be created and react will re-render

Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Kakiz
  • 1,145
  • 1
  • 9
  • 18