user4144415
user4144415

Reputation:

React setState has one character delay

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...).

enter image description here

Is this normal? How can I fix it?

Upvotes: 1

Views: 1165

Answers (3)

Lazar Nikolic
Lazar Nikolic

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

Boussadjra Brahim
Boussadjra Brahim

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

Nam Bui
Nam Bui

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

Related Questions