isMounted() is actually an easy way to solve most problems, however I don't think this is the perfect solution for concurrency problems.
Now imagine that the user clicks a lot on many buttons, or maybe he has a very poor mobile connection. It may happen that, finally, 2 simultaneous requests are pending, and upon completion it will update the state.
If you run query 1 and then query 2, you expect the result of query 2 to be added to your state.
Now imagine that for some reason, query 2 ends before query 1, this will probably make your application inconsistent, because it will display the results of query2, and then request 1, while your last βinterestβ was actually in the query 1 answer.
To solve this problem, it is better to use some Compare and Swap algorithm. This basically means that before issuing the request, you put some node object in the state and upon completion of the request, you compare with reference equality if the node for swaping will still be the node that interests you when the request is completed.
Something like that:
var self = this; var resultNode = {}; this.setState({result: resultNode}); this.getResult().then(function(someResult) { if ( self.state.result === resultNode ) { self.setState({result: someResult}) } }):
With something similar, you will not have a problem with concurrency if the user clicks on the buttons leading to the current requests inside the same component.
source share