I have an event handler which calculates the most voted phrase and prints it every time voting is done. However, after my first vote, my code always gives the last phrase of the array instead of the most voted one. It works after the first vote perfectly. What have I done wrong in my code?
const App = props => {
const [selected, setSelected] = useState(0);
let [votes, setVotes] = useState([0, 0, 0, 0, 0, 0]);
let [mostVotes, setMostVotes] = useState(0);
const handleVote = () => {
let newArray = [...votes];
newArray[selected] += 1;
setVotes(newArray);
let array = new Array(...votes);
let i = Math.max(...array);
for (var a = 0; a < array.length; a++) {
if (votes[a] === i) setMostVotes(a);
}
};
return (
<div>
<h2>Anecdote of the day</h2>
<div>{props.anecdotes[selected]} </div>
<div>has {votes[selected]} votes</div>
<div>
<Button onClick={handleVote} text="vote" />
<Button onClick={randomAnecdote} text="next anecdote" />
</div>
{console.log(mostVotes)}
<h2>Anecdote with the most votes</h2>
<p>{anecdotes[mostVotes]}</p>
</div>
);
};
const anecdotes = [
"If it hurts, do it more often",
"Adding manpower to a late software project makes it later!",
"The first 90 percent of the code accounts for the first 90 percent of
the development time...The remaining 10 percent of the code accounts
for the other 90 percent of the development time.",
"Any fool can write code that a computer can understand. Good
programmers write code that humans can understand.",
"Premature optimization is the root of all evil.",
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."
];