React - Create a Controlled Form

Tell us what’s happening:

Here in the code
this.setState({
submit: this.state.input
});
we use this.state.input to assign value to submit .
It was mentioned in the previous lesson “Use State to Toggle an Element” to not use this inside setState.
Instead use

this.setState(state => ({
counter: state.counter + 1
}));

in a previous exercise toggle visibility we were told to use state.visibility.
So i would like to know the reason why we are using this.state.input.
would state.input work same here…

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36

Challenge Information:

React - Create a Controlled Form

Welcome to the forum @larry123

If you reread the toggle an element lesson, it mentions that:

state updates may be asynchronous - this means React may batch multiple setState() calls into a single update. This means you can’t rely on the previous value of this.state or this.props when calculating the next value.

If you try using state.input you will receive an error, which can look up in the console.

Happy coding

teller thanks for responding fast.
that’s my contention.
in the code
this.setState({
submit: this.state.input
});
we are using “this” inside setState.

for the counter
this.setState(state => ({
counter: state.counter + 1
}));
we are not using “this” inside setState.

in also we are not using this inside setState…
toggleVisibility() {
this.setState(state => {
if (state.visibility === true) {
return { visibility: false };
} else {
return { visibility: true };
}
});
}

When to use this inside setState and when to not use…