I encoded my ReactJS AJAX requests as follows:
this.setState({ isLoading: true, results: null }); $.get(ajaxUrl, function(results) { this.setState({ isLoading: false, results: results }); }.bind(this));
This is just an example, it does not have error handling, throttling, query cancellation, etc. But the point is this. I basically ask to set some state and then execute the request.
Looking at some other code on GitHub, I noticed that some people write their AJAX calls in the setState callback:
this.setState({ isLoading: true, results: null }, function() { $.get(ajaxUrl, function(results) { this.setState({ isLoading: false, results: results }); }.bind(this)); }.bind(this));
Is there a good reason for this? The docs say :
There is no guarantee that setState calls will work synchronously, and calls can be collected to improve performance.
Thus, there is no guarantee that setState changes state before returning, but I see no mention of the fact that various setStates may not perform properly. So the worst thing that can happen is that the loading state is not working. Is this what the latest style is trying to solve? Is there any other risk that I do not see?
Tobia source share