Home > Back-end >  How to get checkbox value immediately after setting the state in react
How to get checkbox value immediately after setting the state in react

Time:03-31

I want the checkbox value immediately after setting the state. on the below code i want the checkbox value inside the handelchange after setting the state I have added console over there

state = {
status: false,
}

handleChange = (event) => {
this.setState((prevState) => {
   return {
      ...prevState,
      status: !prevState.status
   }
})
 ====console.log(this.state.status)====//if it checked and set i should get true
 }


<Form.Check
type="checkbox" 
label="Consigne temporaire"
value={this.state.status}
onChange={this.handleChange}
 />

CodePudding user response:

You can pass a callback as the second argument to this.setState, which is guaranteed to run after the state has been updated (see the docs on setState)

this.setState((prevState) => {
  return {
     ...prevState,
     status: !prevState.status
  }
}, () => {
  console.log(this.state.status)
})

CodePudding user response:

You can use useEffect or componentDidUpdate and bind the checkbox state with it.

state = {
status: false,
}

componentDidUpdate(prevProps, prevState) {
  if (prevState.status !== this.state.status) {
    console.log('Checkbox State change',this.state.status)
  }
}

handleChange = (event) => {
this.setState((prevState) => {
   return {
      ...prevState,
      status: !prevState.status
   }
})
 ====console.log(this.state.status)====//if it checked and set i should get true
 }


<Form.Check
type="checkbox" 
label="Consigne temporaire"
value={this.state.status}
onChange={this.handleChange}
 />
  • Related