score:17

Accepted answer

setState is asynchronous in that this.state will not be updated right away. The short answer to your quandary is use the callback (the second parameter to setState) which is invoked after the internal state is been updated. For example

this.setState({page: page}, function stateUpdateComplete() {
    console.log(this.state.page)
    this.findByName();
}.bind(this));

The longer answer is that after you call setState, three functions are called (see here for more details about each https://facebook.github.io/react/docs/component-specs.html):

  • shouldComponentUpdate this allows you to inspect the previous and new state to determine whether the component should update itself. If you return false, the following functions are not executed (although the this.state will still be updated within your component)
  • componentWillUpdate this gives you a chance to run any code before the new state is set internally and rendering happens
  • render this happens between the component "will" and "did" functions.
  • componentDidUpdate this gives you a chance to run any code after the new state is set and the component has re-rendered itself

score:0

Using nameless functions this code can be written in a shorter format.

myReactClassFunction = (param) => {
  this.setState({
    key: value,
  },
  () => this.myClassFunction());
}

score:2

When calling this.setState the new state isn't set directly, React puts it in a pending state which by calling this.state can return the old state.

This is because React might batch your state updates and therefore offers no guarantee that this.setState is synchronous.

What you want to do is called this.findByName() within componentDidUpdate, componentWillUpdate or through the callback offered as a second argument to this.setState depending on your use case. Note that the callback to this.setState won't be fired until after your call has passed and the component has re-rendered itself.

Furthermore in your case you could pass a function do this.setState instead of doing a variable dance to increase readability.

this.setState(function (prevState, currentProps) {
    return {page: prevState.page + 1}
}, this.findByName);

Related Query

More Query from same tag