Home > Net >  checkbox don't get first check in react
checkbox don't get first check in react

Time:05-11

I'm sorry I'm not that good at English and this is my first time to use this website. So My question might look a little bit strange.

I just wanna make a checkbox. When it got check signal, then I want to make it to express true, and when the checking is removed, then it should express false. But when I use console.log, I found that the first checking don't make any change and after checking is worked like toggle. I don't know why. My code is below, and in third picture, I just checked three time.

enter image description here

enter image description here

enter image description here

CodePudding user response:

The setState function is async, so in the following lines of code inside your updateIsAgreeInfo the state isn't updated yet
You have to store the new value in a variable

Moreover, when setting a state based on old state value, you should use a function in setState instead of the raw value:

setIsAgreeInfo((oldValue) => !oldValue);

CodePudding user response:

Change your updateIsAgreeInfo to this:-

const updateIsAgreeInfo = () =>{
    setIsAgreeInfo(!isAgreeInfo);
    console.log(isAgreeInfo)
    signupPayload.isAgreeInfo = !isAgreeInfo;
}

or send event as a params in updateIsAgreeInfo and then access the current checked value of checkbox using event.target.checked. like:-

const updateIsAgreeInfo = () =>{
    setIsAgreeInfo(event.target.checked);
    console.log(event.target.checked)
    signupPayload.isAgreeInfo = event.target.checked;
}
  • Related