Reputation:
I have a form with a few fields created with react and an onChange
handler:
<Form.Control id="user_email" required type="email" onChange={this.handleChange} name="email"/>
the Handler:
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
})
}
When I log this.state
in the handler, and also e.target.value
, this.state.email
is always one character behind e.target.value
(budget
is another field...).
Is this normal? How can I fix it?
Upvotes: 1
Views: 1165
Reputation: 4394
I suggest not setting state in onChange event, since every keypress, you will call setState which can be on some older browsers really bad for performance. Instead you can use lodash's debounce in order to setState some time after last keypress.
handleChange = debounce(e => this.setState({
[e.target.name]: e.target.value,
}))
<Form.Control id="user_email" required type="email" onChange={e => this.handleChange(e)} name="email"/>
Upvotes: 0
Reputation: 1
Your setState mutation could not be gotten immediately, so you could add a callback to get the new values applied :
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
}, ()=>{
console.log(this.state) //logs the new values
})
}
Upvotes: 1
Reputation: 1361
setState
is asynchronous, if you want to log what you just set in the state you need to pass a callback as second argument of the setState:
this.setState({somestate: somedata}, () => console.log(this.state.somestate))
Upvotes: 3