Why can't i update the input based on previous state?[React]

Tell us what’s happening:
in the code, i have to use “this” keyword with the current state to update the value and it works. However, the same is not true when i do the change using previous state like this: this.seState(prevState=>({ submit: prevState.input }))

why isn’t it working? is’nt it better to use the previous state rather than using the current because of the async nature of react?
Your code so far


class MyForm extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: '',
    submit: ''
  };
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
  this.setState({
    input: event.target.value
  });
}
handleSubmit(event) {
  event.preventDefault()
  this.setState({
    submit: this.state.input
  });
}
render() {
  return (
    <div>
      <form onSubmit={this.handleSubmit}>
        <input
          value={this.state.input}
          onChange={this.handleChange} />
        <button type='submit'>Submit!</button>
      </form>
      <h1>{this.state.submit}</h1>
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Create a Controlled Form

Link to the challenge:

Hi @shahid.alam57

I believe you are getting an error because of the spelling of this.setState. Looks like you misspelled it.

1 Like

oh. i made this post in a hurry so there are some spelling mistakes here . but in the code editor, this.setState(prevState=>({ submit: prevState.input })) did’nt work either. thanks for the reply!

Well, it worked for me.

1 Like

I just received this advice from a react dev moderator here about methods within the component:

When this lesson was written, you had to bind this to your class methods in the constructor. I’m saying that if you make it an arrow function, then you don’t have to because the method will just inherit the class’ this . Declare it like this:

iterator = () => {

Or don’t. Either works.

So i am suspecting the => nature of the prevState assignment means it doesn’t need ‘this’ in modern react.

(be warned I’m a noob, but the above quote looks relavant to me. )

1 Like