So I have been struggling to pass a callback to this.setState()
, because I was doing this way :
this.setState({ anyState }, this.anyFunction());
The function was called, but it wasn't called really after the state was updated. In result, as I was also updating the same anyState
in my anyFunction
, there was some kind of a conflict between the two state updates, and only the first one was effective.
Then I discovered that I had to do either
this.setState({ anyState }, () => this.anyFunction());
either
this.setState({ anyState }, function() { this.anyFunction() });
to make things work properly.
Why so ? Why seems my first approach wrong ?
In the first example, you are using the result of the function as a second argument.
Say this.anyFunction
returns a constant "some_text"
, using
this.setState({ anyState }, this.anyFunction());
is the same as using
this.setState({ anyState }, "some_text");
In the second example, you are actually passing a callback. Or a function as an argument. That function is not executed yet, it will be executed at the end of setState().
For more information about asynchronous programming and callbacks, you can watch this talk: https://javascript-conference.com/javascriptecmascript/asynchronicity-concurrency/