I am trying to make a basketball scoreboard app in React and have each team as it’s own object with score, field goals made, and field goal attempts as properties. I have buttons that increment all of these properties and I am trying to create a button to account for missed shots using setState on field goal attempts(fga), but it also updates the state for the other properties resetting their state to 0. Is there a way to use setState on a specific property without touching the rest?
Object:
const [team1, setTeam1] = useState({
score: 0,
fgm: 0,
fga: 0,
threePm: 0,
});
Button:
<button
id="miss"
onClick={() =>
setTeam1({
fga: team1.fga + 1,
})
}
>
Miss
</button>
3
Answers
Take the previous state, spread it, and add the updated property to create the new state:
When creating a new state, based on the previous state, it’s better to use and updater function. The updater function is called with the previous state. Take the previous state, spread it into a new object, and add the updated property:
Simple, use a spread operator to make a copy of the previous state and set it to your new state, then we set the new property like so: