Kamyar Parastesh Kamyar Parastesh - 10 months ago 63
React JSX Question

React: Delay in updating the state

Consider the following code. I want to keep the last character of the text in the textfield get stored in a state called

lastChar
. To do this, i did the following code?

define(["react","react-keydown"], (React,keydown) => {

var TypingContainer = React.createClass({
getInitialState: function() {
return {text: '',lastChar:''};
},
handleChange: function(e) {


console.log('lastChar typed is:'+ e.target.value.slice(-1));

this.setState({lastChar: e.target.value.slice(-1)});

console.log('lastChar in state is:'+ this.state.lastChar);


}

,
render: function() {
return(
<div>
{this.props.candidateWord}
{this.props.message}
<input
className="typing-container"
value={this.state.message}
onChange={this.handleChange}



/>

</div>
);
}
})
return TypingContainer;
});


for instance, if the user type
hello
, i expect to see the last character in both
e.target.value.slice(-1)
and
this.state.lastChar
the same as
o


meanwhile
lastChar
shows
l


In other word lastChar is always one char before exact value?

why does it happen? and how can i fix it?

Ved Ved
Answer Source

You will not get the updated value of state just after calling setState(). This is because as soon as setState() is called view is re-rendered. So it is better to check the updated value inside render.

 render: function() {
    console.log('lastChar in state is:'+ this.state.lastChar);
      return(
         <div>
           {this.props.candidateWord}
           {this.props.message}
            <input
              className="typing-container"
              value={this.state.message}
              onChange={this.handleChange}
            />

         </div>
      );
    }

Or,

this.setState({lastChar: e.target.value.slice(-1)}, function() { console.log(this.state.lastChar)});