2

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?

Jeff
  • 7,767
  • 28
  • 85
  • 138
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – zero298 Aug 10 '21 at 15:40

1 Answers1

13

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)}, ()=> { 
    console.log(this.state.lastChar)
});
Ved
  • 11,837
  • 5
  • 42
  • 60
  • 4
    true. you could also access the changed value in the setState callback function like `this.setState({lastChar: e.target.value.slice(-1)}, function() { console.log(this.state.lastChar)}.bind(this));` – Richard Rutsche Apr 06 '16 at 11:27