Reputation: 85
This example simulates a coin toss.
I would like to randomize the initial state of the coin. The first time the page is loaded it could show heads. The next time, tails. To do so, I am using a random number generated by the Math method and a conditional to determine the face of the coin based on the random number (even number shows heads, odd shows tails).
The value needs to be displayed upon the initial render.
I also want to store the value in state using React's Hooks to use later in my app. How can I set a randomized initial state value using hooks?
Here is the code that I am working with. It currently does not function and I'm not sure what I am doing incorrectly to achieve my goal:
import React, { useState } from 'react';
import './App.css';
function App() {
const [coin, setCoin] = useState(randomizePlayer())
const randomizePlayer = () => {
let number = Math.floor(Math.random() * 10) + 1
return (number % 2 === 0) ? setCoin('Heads') : setCoin('Tails')
}
return (
<div className="App">
The coin is showing {coin}
</div>
);
}
export default App;
I'm brand new to the hooks API and am using this exercise to learn.
Any help is appreciated!
Upvotes: 2
Views: 4777
Reputation: 5852
I would rewrite this code as follows:
const randomizePlayer = () => {
const number = Math.floor(Math.random() * 10) + 1
return (number % 2 === 0) ? 'Heads' : 'Tails'
}
function App() {
const [coin, setCoin] = useState(randomizePlayer())
return (
<div className="App">
The coin is showing {coin}
</div>
);
}
randomizePlayer
does not need to call setState
; let it just return a value. useState
can use that value as its initial state.
Also to clarify: useState
gets called just once. If you want coin
to have a different value, the way to do that with this setup is to remount the component (reload the page).
Upvotes: 3