React checkbox - Onchange checkbox, coming undefined for 1st time

Viewed 374

React checkbox - Onchange ouput as undefined for 1st click(time). After that showing valid true or false output.I googled this issue but not solving the problem.

Please help, What i'm doing wrong here.

I defined checked as false in the State:

  constructor() {
        super();
        this.state = {
         formFields: {
            checked: false,
          },
        };
      }

Handling the checkbox:

handleCheckBox = (e) => {
    this.setState({ checked: !this.state.checked });
    console.log("checked", this.state.checked);
    // this.setState({ checked: !this.state.formFields.checked });
    // console.log("checked", this.state.formFields.checked);
  };

destructuring:

const { ...formFields } = this.state;

In the form checkbox input as follows:

<input
     type="checkbox"
     checked={formFields.checked}
     onChange={this.handleCheckBox}
 />

On check for first time the output as follows: output

1 Answers

This is because setState works asynchronously. To get the behaviour that you want pass the console.log as a callback in the setState function:

this.setState(
     { checked: !this.state.checked }, 
     () => console.log(this.state.checked)
);

The callback will be called after the state has been updated. By calling console.log() outside of the callback, javascript will run the console.log before the state has updated.

This is because no matter what, the current call stack has to be cleared before any async calls are made.

Read more here: https://developer.mozilla.org/en-US/docs/Glossary/Call_stack#:~:text=A%20call%20stack%20is%20a,from%20within%20that%20function%2C%20etc.

Related