setState before returning any value

2486 views reactjs

So, I have a property in the state of a component called "method" which is set to an empty string (""), and a function called selectMethod ==>

  selectMethod = (e) => {
      const x ="return-data");  
      this.setState({method: x});  

which is fired when I click a button

<button onClick={this.selectMethod} return-data="test">SELECT</button>

What I expected to be shown in the console is "test". but when I clicked the button just the empty string is shown and then when I click on the button one more time the "test" word is shown. What I'm trying to do is to make the property method set to "test" before is gets consoled and make test show up on the console from the first click. I don't know why it's doing this. I mean "method" should be set to "test" before it gets consoled.

answered question

1 Answer


setState doesn't happen immediately, so you can't rely on it being the new value in the same run loop like that. However, it does take a callback as its second argument that you can use if necessary. Found a short little medium post about this for ya -

posted this

Have an answer?


Please login first before posting an answer.