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: