I'm trying to use React hooks (useState & useEffect) in a component to show a vote count. After the user clicks up/down the 'vote' state should be increment or decremented and then the app makes an API call to PATCH the votes count in the database. The original vote count is coming from props passed from the parent component. But for some reason, the initial state for the votes is always 0 -- even though when I console.log the props it shows the correct number of votes?
PATCH request seems to be working fine, but something with hooks I think is wrong. Thanks in advance for any help I can get on this!
export default function Votes(props) {
const { item, voteCount, itemType } = props
const [votes, setVotes] = useState(voteCount || 0)
useEffect(() => {
if (itemType == 'question') {
questionApiService.updateQuestionFields({
questionId: item.id,
questionFields : { votes: `${votes}` }
})
} else if (itemType === 'answer') {
console.log('answer')
// questionApiService.updateAnswerFields({
// answerId: item.id,
// answerFields: { votes: votes }
//})
}
}, [votes])
const handleClick = e => {
e.currentTarget.id === increment
? setVotes(prevCount => prevCount + 1)
: setVotes(prevCount => prevCount - 1)
}
return (
<div className=QuestionPage__votes-count>
<button id=increment onClick={handleClick}>
<FontAwesomeIcon icon={faCaretUp} size=2x />
</button>
{votes}
<button id=decrement onClick={handleClick}>
<FontAwesomeIcon icon={faCaretDown} size=2x />
</button>
</div>
)
}