unknown user
unknown user

Reputation: 21

event.target.value is giving value before change

when i am trying to change the state of input field using onchange e.target.value is giving the value before change

 <form onSubmit={this.handleSubmit}>
      <input type='text'value={this.state.search} onChange={this.onChange}/>
      <button type='submit' >Search</button>
 </form>

the onchange function looks like this

onChange=(e)=>{ var search=e.target.value;
    this.setState({search})
    this.props.dispatch({type:'SUGG',payload:this.state.search,})
}

I tried logging both e.target.value and this.state.search e.target.value is showing correct value but state is showing previous value

edit: I got it setstate is async function so the previous value is getting logged

Upvotes: 0

Views: 2384

Answers (2)

Thomas Hintz
Thomas Hintz

Reputation: 1

@Jai's answer will work but assuming you don't have other operations that might modify this.state.search after calling this.setState you can just make the call to dispatch passing in search directly.

For example:

payload:search

And in full:

onChange=(e)=>{ var search=e.target.value;
    this.setState({search})
    this.props.dispatch({type:'SUGG',payload:search,})
}

The issue is that setState is asynchronous. Calling it does not immediately change this.state so you can either use search directly or use a callback in setState.

Upvotes: 0

Jai
Jai

Reputation: 74748

Try dispatching from callback of setState:

this.setState({search}, ()=>{
       this.props.dispatch({type:'SUGG',payload:this.state.search,})
});

It will update the state first then it will execute the callback because of the async nature of setState.

Upvotes: 2

Related Questions