kalecrush
kalecrush

Reputation: 71

React: Input onChange to update state step behind

I have an input with onChange attribute which calls a function handleChange, which updates state with the new value that was typed in the input.

Issue 1 - When state is logged at the end of handleChange it contains the old state, or one input letter behind (will log 'ca' when you type 'cat').

Issue 2 - Without event.persist the event is 'synthetic' and doesn't contain the value. Is this acceptable to keep the persist or should this be structured differently?

Input has:

onChange={this.handleChange}

Which calls function:

handleChange = (event) => {
    event.persist() // without this the event is 'synthetic'

    const newTerms = {...this.state.terms}
    newTerms.text = event.target.value

    this.setState({terms: newTerms})

    console.log('state', this.state) //logs the previous state
}

this.state.terms.text should be changed:

this.state = {
    terms: {
        text: '',

Upvotes: 1

Views: 2910

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174447

state update is asyncronous. What you want is this:

this.setState({terms: newTerms}, () => console.log('state', this.state))

Even without persist the event contains the value inside the event handler. This is only true in a synchronous context, so you should not pass the event to setState or other asynchronous methods.

Upvotes: 2

Related Questions