0

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'.

Soonk
  • 332
  • 2
  • 14
  • 1
    The logged values are undefined because... calling a state setter won't reflect the change immediately, only on next render – CertainPerformance Mar 27 '22 at 02:17
  • @CertainPerformance Thank you for leaving a reply. At least I could have one answer which gives me a hint. – Soonk Mar 27 '22 at 02:22

0 Answers0