handleChange() function causing crash for some reason

I don’t understand why my handleChange() function isn’t working. As soon as I start typing anything into the input text box, my whole application crashes. My submitMessage() function uses the same syntax, but it seems to work fine. I’ve tried re-writing my function as to simply pass an object to setState instead of a function, and that works fine. However, I want to know what exactly is wrong with my implementation here. I would appreciate any advice. Thank you!


class DisplayMessages extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: '',
    messages: []
  }
  this.handleChange = this.handleChange.bind(this);
  this.submitMessage = this.submitMessage.bind(this);
}

handleChange(event){
  this.setState((state,props)=>{
    return {
      input: event.target.value,
      messages: state.messages
    }
  });
}

submitMessage(){
  this.setState((state,props)=>{
    return {
      input: '',
      messages: [...state.messages,state.input]
    }
  });
}

render() {
  let temp=this.state.messages.map(
    (i) => {
      return <li key={i}>{i}</li>
    }
  )
  return (
    <div>
      <h2>Type in a new Message:</h2>
      <input onChange={this.handleChange} value={this.state.input}/>
      <button onClick={this.submitMessage}>Click</button>
      <ul>
      {temp}
      </ul>
    </div>
  );
}
};
  **Your browser information:**

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

Challenge: Manage State Locally First

Link to the challenge:

  1. Because of the updater function for the handleChange. You can read more about it in the post below.

setState and event.target

  1. state.messages now has to be using this (without the updater function)
1 Like

That was helpful – thank you for the reply. If I understood correctly, the lesson to be learned here is to avoid using updater functions with setState, and to instead pass it an object directly?

Yes, at least with the version of React that the challenges are using. It would have worked with React 17 and up.

Edit: If you do need an updater function in React 16 you can use one of the methods explained in the thread I linked to.

One option is to use event.persist() or save the value at the top of the handler function (only when an updater function is needed).

1 Like

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