I'm working on a small application with which you can keep track of some game scores.
The game is played between two players. A player can score points but can also incur a penalty. Instead of substracting the penalty from the player's score, it gets added to his opponent's score. The opponent should also get the next turn.
I setup a demo that implements the above description: https://codepen.io/anon/pen/ybLQvR
As you can see in the demo it doesn't quite work: when a player incurs a penalty he gets awarded the penalty, instead of his opponent.
This is due to
I see what you're saying now. To my undestanding what you are trying to do is make sure that the setState method has been executed before another setState method.
Now the docs have this to say on the matter:
The second parameter is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.
So by their recommendations you should use
componentDidUpdate(). So how is the question now.
That is the method signature. So we can see here that the previous state gets passed in, and we now have access to the current state via
See codepen for the answer.
Basically - I turned the
changeTurn into functions that were just snippets of the
setState. This means we can combine them together with or state changes to make one atomic operation. And they can be reused without adding complicated default parameters for different scenarios.
Secondly, I added in functions which applied these methods in order to set the state. These are what the buttons use!
Finally in the
componentDidUpdate function there is now a chance to apply actions based on the current action that is being executed. Do not add a setState for the default action, otherwise you'll get an infinite loop of updating......