Doubt this.setState

Tell us what’s happening:
What’s the difference between:

  handleSubmit(event) {
    event.preventDefault()
    this.setState({
      submit: this.state.input
    });
  }

and

  handleSubmit(event) {
    event.preventDefault()
    this.setState(state => {
      submit: state.input
    });
  }

Why the second one does not work?
Thanks in advance

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}>
        { /* change code below this line */ }
      <input value={this.state.input} onChange={this.handleChange}>
      </input>
        { /* change code above this line */ }
        <button onClick={this.handleSubmit} type='submit'>Submit!</button>
      </form>
      { /* change code below this line */ }
<h1>{this.state.submit}</h1>
      { /* change code above this line */ }
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36.

Challenge: Create a Controlled Form

Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react/create-a-controlled-form

The second example, you are setting the state to use a callback function and ensure that React doesn’t bunch up state that is similar. It’s a good idea, but I’m unsure about it being on a submit like that. What are you also trying to grab from the state and submit it with?

@Pen.Apple The reason it does not work as you expect, is because you may not understand how all the ins-and-outs of how arrow functions work.

If you want to return an object using an arrow function you have two choices:

Explicit return:

const func = param => {
  return {
    prop1: 'value 1',
    prop2: 'value 2'
  };
};

OR
Implicit return:

const func = param => ({
  prop1: 'value 1',
  prop2: 'value 2'
});

Note in the second example, the object returned is surrounded by parentheses. This tells JavaScript to return the value inside.

1 Like