I'm trying to learn hooks in React.js by rewriting a "Rock Paper Scissor" game. I can't get the winner evaluated at the same time when I press the choosen button. This is my code (it's a shorter code where I compare just the player pressing the paper button):
function App() {
const weapons = ["paper","scissors","rock"];
const [choice, setChoice] = useState({
playerOne: "",
playerTwo: "",
winner: ""
})
const chooseWeapon=(weapon)=>{
setChoice({
playerOne: weapon,
playerTwo: weapons[Math.floor(Math.random() * 3)],
winner: getWinner(choice.playerOne,choice.playerTwo)
})
}
const getWinner = (player1,player2)=>{
if(player1==="paper"){
if(player2==="scissors"){
return("player two won")
} else if(player2==="rock"){
return("player one won!!!!!")
}
}
}
return (
<div className="App">
<h1>Rock scissors lizard</h1>
<h2>player one:{choice.playerOne}</h2>
<h2>player two:{choice.playerTwo}</h2>
<h1>{choice.winner}</h1>
<button onClick={()=>chooseWeapon("paper")}>paper</button>
<button onClick={()=>chooseWeapon("scissors")}>scissors</button>
<button onClick={()=>chooseWeapon("rock")}>rock</button>
</div>
);
}
export default App;
Basically when I click on the "paper" button, I get rendered on the screen choice of each player, but I will get the winner status only after I press it again. The winner render is always one step behind. How can I fix this?
Thank you guys!