0

I have added a property to state.

 const[person, setPersonObj] = useState({});
setPersonObj({...person, age: 24});

and using in jsx and i can see the age.

<input type="text" value = {person.age} /> 

but when I am again destructing person object it is not showing me the age property.

const personObj = {...person};
personObj.age is undefined; 

All this is done in one event.

Vivek
  • 176
  • 7

1 Answers1

0

I notice that you are using useState hook like this right?

const [personObj, setPersonObj] = useState(...);

So the problem here is when you use setPersonObj, the state personObj will update with new property age, not the variable person. So when again you set personObj as person, which not contain age, it will not contain age property.

  • I have edited the question, please can you suggest something – Vivek Oct 27 '20 at 07:41
  • Ok, so there is another case, this is when you use `const personObj = {...person}` right after you use `setPersonObj`, at this time the `person` state haven't update yet and you won't get the `age` property, so you do need to use a callback to get the new value of `person` after it get updated. You can use `useEffect` hook. Take a look at this link [How to use callback for setState](https://stackoverflow.com/a/56247483/7698877) – Nguyễn Khương Oct 27 '20 at 07:51
  • but I can see that person.age in JSX, it has set the value in textbox. so person state is set and it has value person.age but why not when destructing the same object. – Vivek Oct 27 '20 at 07:53
  • well, yes it's true, because rerender phase always happen after your state updated and you can see the `age` property there, try `console.log(person)` before `const personObj = {...person}` and `{console.log(person)}` before your jsx, you can see two different value of `person` and the order of their log – Nguyễn Khương Oct 27 '20 at 08:03