What did I do wrong in my handleChange method?

I know that the issue arises when I pass in the state as an argument in this.setState.

  handleChange(event) {
    this.setState(state => ({
      input: event.target.value
    }))
  }

I just don’t understand why it throws an error by passing in the state

  **the Whole code**

class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  // Change code below this line
  this.handleChange = this.handleChange.bind(this);
  // Change code above this line
}
// Change code below this line
handleChange(event) {
  this.setState(state => ({
    input: event.target.value
  }))
}
// Change code above this line
render() {
  return (
    <div>
      { /* Change code below this line */}
      <input value={this.state.input} onChange={this.handleChange} />
      { /* Change code above this line */}
      <h4>Controlled Input:</h4>
      <p>{this.state.input}</p>
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36

Challenge: Create a Controlled Input

Link to the challenge:

Its because of event pooling. setState is async. So the callback will pop from the stack even before setState is executed. What event pooling is it will nullify all the event fields right after callback is finished. So when setState access the event object its fields will be null.You can prevent this by creating a closure or e.persist()

handleInputChange(e) {
  const val = e.target.value;

  this.setState(function (prevState, props) {
      return {
        searchValue: val
      }
  })
}

or

handleInputChange(e) {
  e.persist();

  this.setState(function (prevState, props) {
      return {
        searchValue: e.target.value,
      }
  })
}
1 Like

It should be noted that this is specific to React 16 and below. 17 and 18 do not suffer from this “quirk”.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.