JavaScript React Components Managing State and Data Flow Building the Statistics Component

Jeremy Ashcraft
Jeremy Ashcraft
Front End Web Development Techdegree Student 13,087 Points

How do the totalPoints keep updated using Guil's solution?

Guil's Solution: const totalPoints = props.players.reduce( (total, player) => { return total + player.score; }, 0);

With Guil's solution, shouldn't totalPoints be assigned a value only once (at the time the stats component is rendered into the DOM)?

Yet the total points score updates every time the score changes.

1 Answer

Jason Pallone
Jason Pallone
9,695 Points

The Reduce method takes 2 arguments, accumulator and the item it is currently looping through in the array, so by returning total + player.score we are using dot notation on each player object in the array to get their individual scores. Each time reduce loops through, it adds the player score for the current array index to total. Then at the end once it has looped through the whole array, you have the total points for each player combined returned to your totalPoints variable. Now whenever you update a player score, that is changing the state, which makes the component re render and update the state, reflecting a new total for totalPoints. If you need me to clarify more please just ask! Hope this helps!