This doesn't give the answer please don't mark this question as a duplicate. It seems similar but different. Please Please Please stop marking this question as duplicate.
My Question
I wanted to bring two values with one useState in React like below. enter image description here
To update the information, and update the state, I wrote a code as below.
const [userInfo,userInfoHandler] = useState({name:undefined,age:undefined });
const addUserHandler = (event)=>{
userInfoHandler(prev=>{
const prevObj = {...prev};
prevObj.name=event.target[0].value;
prevObj.age=parseInt(event.target[1].value);
return prevObj
})
event.preventDefault();
console.log(userInfo);
// userInfoHandler(prev=>{return {name:undefined,age:undefined}})
}
However, when I console.log userInfo above, it logs undefined which is the value before update.
It returns correct value only when I submit twice.
Why is that?
I understand that normally, 'onChange' is set for each input. but I wanted to update my userInfo state at once.
how do I work around it instead of setting two Onchange for both 'input'.