1

I've got some confusion with React's event handler

I have a component like this, with handleChange handling onChange event:

var SearchBar = React.createClass({
    getInitialState(){
        return {word:''};
    },
    handleChange: function(event){
        this.setState({word:event.target.value});
        alert(this.state.word);
    },
    render: function () {
        return (
            <div style={{width:'100%',position:'0',backgroundColor:'darkOrange'}}>
                <div className="header">
                    <h1>MOVIE</h1>
                </div>
                <div className="searchForm">
                    <input className="searchField" onChange={this.handleChange}
                        value={this.state.word} type="text" placeholder="Enter search term"/>
                </div>
            </div>
        );
    }
});

It does work, but not the way I expect. In textfield, when I type the first character, it alerts empty string, when the second character is typed, it alerts a string with only first character, and so on, with string length of n, it alerts the string with n-1 length

What did I do wrong here? How should I fix it?

3 Answers 3

2

Use like this,

Js:

   this.setState({word:event.target.value}, function() {
    alert(this.state.word)
   });

Working Jsbin

Sign up to request clarification or add additional context in comments.

Comments

1

I think it has something to do with state handling inside React.

I can come with two options to handle it.

Either:

handleChange: function(event) {
  this.setState({word: event.target.value});
  window.setTimeout(function() {
    alert(this.state.word);
  }.bind(this));
}

Or:

alertCurrentValue() {
  alert(this.state.word);
},
render: function () {
  this.alertCurrentValue();
  return ( ... )
}

Comments

0

Praveen Raj's answer is definitely the right way to go. Here is the documentation I found from the official React website on why you should access this.state inside the callback rather than right after setState():

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.