As a learning exercise I am trying to code a generic feedback application that counts the number of "good"(+1), "bad"(-1) and "neutral"(0) button clicks, the sum of their values, the average value and positive percentage.
Now I am noticing that the sum –— and only sum! –— value somehow lags one button click behind the events, as the first click, say, on "good" button would produce an average value of "NaN". I assume the sum is somehow still "zero". The rest of the values are being updated as expected.
Could anyone please explain what am I missing here? The App.js code is as follows:
import React, {useState} from 'react'
const Button = (props) => {
return (
<>
<button onClick = {props.handleClick}>{props.text}</button>
</>
)
}
const App = () => {
const [good, setGood] = useState(0)
const [neutral, setNeutral] = useState(0)
const [bad, setBad] = useState(0)
const [all, setAll] = useState(0)
const [sum, setSum] = useState(0)
const [average, setAverage] = useState(0)
const [positive, setPositive] = useState(0)
const [history, setHistory] = useState([])
const handleGoodClick = () => {
setAll(all + 1)
setSum(sum + 1)
setGood(good + 1)
setHistory(history.concat(1))
setPositive(good / all)
setAverage(sum / all)
}
const handleBadClick = () => {
setAll(all + 1)
setSum(sum - 1)
setBad(bad + 1)
setHistory(history.concat(-1))
setPositive(good / all)
setAverage(sum / all)
}
const handleNeutralClick = () => {
setAll(all + 1)
setNeutral(neutral + 1)
setHistory(history.concat(0))
setPositive(good / all)
setAverage(sum / all)
}
return (
<>
<h2>Give Feedback</h2>
<Button handleClick = {handleGoodClick} text = {'good'}/>
<Button handleClick = {handleNeutralClick} text = {'neutral'}/>
<Button handleClick = {handleBadClick} text = {'bad'}/>
<h2>Statistics</h2>
<p>Good: {good}</p>
<p>Neutral: {neutral}</p>
<p>Bad: {bad}</p>
<p>All: {all}</p>
<p>Average: {average}</p>
<p>Positive: {positive}</p>
<p>History: {history.join(' ')}</p>
</>
)
}
export default App