In the code below, I've handled the concurrent change of multiple state variables by using a unique global "State", but I don't think it is the best way to do so.
Can anybody suggest me how to change multiple states without keeping them together as I did?
Here's the working code with the "complex state"
import { useState } from 'react'
const App = () => {
const [state, setState] = useState({
good: 0,
neutral: 0,
bad: 0,
tot: 0,
weights: 0,
avg: 0,
posPercent: 0
});
const handleGood = () => {
setState({
...state,
good: state.good +1,
tot: state.tot +1,
weights: (state.good+1)*1 + state.neutral*0 + state.bad*(-1),
avg: ((state.good+1)*1 + state.neutral*0 + state.bad*(-1))/(state.tot +1),
posPercent: ((state.good+1)*100)/(state.tot+1)
});
}
const handleNeutral = () => {
setState({
...state,
neutral: state.neutral +1,
tot: state.tot +1,
weights: state.good*1 + (state.neutral+1)*0 + state.bad*(-1),
avg: (state.good*1 + (state.neutral+1)*0 + state.bad*(-1))/(state.tot +1),
posPercent: ((state.good)*100)/(state.tot+1)
});
}
const handleBad = () => {
setState({
...state,
bad: state.bad +1,
tot: state.tot +1,
weights: state.good*1 + state.neutral*0 + (state.bad+1)*(-1),
avg: (state.good*1 + state.neutral*0 + (state.bad+1)*(-1))/(state.tot +1),
posPercent: ((state.good)*100)/(state.tot+1)
});
}
return (
<div>
<h1>give feedback</h1>
<button onClick={handleGood}>
good
</button>
<button onClick={handleNeutral}>
neutral
</button>
<button onClick={handleBad}>
bad
</button>
<h1>statistics</h1>
<p>good {state.good}</p>
<p>neutral {state.neutral}</p>
<p>bad {state.bad}</p>
<p>all {state.tot}</p>
<p>average {state.avg}</p>
<p>positive {state.posPercent} %</p>
</div>
)
}
export default App