2
cb219
4y

Dealing with React's setState and looking through all the possible lifecycle methods was so frustrating today.
It should have been a simple thing to disable a button, via the disabled prop, on click. I thought it would be enough to say
this.setState({ disableButton: true });
someSynchronousCode();
this.setState({ disableButton: false });
in the handler ... but it wasn't. The button would still be active for about a second after clicking. I tried several things like converting the synchronous code to a promise, trying componentDidUpdate with a comparison. It all failed. Interestingly enough removing the 2nd setState immediately disabled the button, though making it permanent.🙄
I've found a solution which seemed a bit hacky, changing the state back depending on another variable in the render method.
It seems so wrong, but it was the only solution I found after several hours.

Comments
  • 1
    Maybe your problem is that setstate is async and you are treating it as sync code? Try putting your sync code in the callback as a second argument to setstate
  • 1
    @Rambolus I know that it's async, also tried to put the sync code and the second setState as callback of the first setState, just like your suggestion. Still failed. Somehow achieved the expected behavior, but still there must be a better way than what I did. I can only imagine myself looking at my code in 1 year and asking myself "why did I write this HERE?"
  • 0
    This seems like more work than rxjs.
Add Comment