From 241e1b0484c47a495c8344ca7a962d569e7c2f12 Mon Sep 17 00:00:00 2001 From: husseinizaid Date: Wed, 13 Dec 2023 19:38:40 -0500 Subject: [PATCH] This commit centralizes the leaderboard sorting logic within the useEffect hooks in the ScuntLeaderboard component. Previously, sorting was redundantly applied in individual child components --- .../ScuntLeaderboard/ScuntLeaderboard.jsx | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/client/src/pages/ScuntLeaderboard/ScuntLeaderboard.jsx b/client/src/pages/ScuntLeaderboard/ScuntLeaderboard.jsx index 0d292d9b..0b206879 100644 --- a/client/src/pages/ScuntLeaderboard/ScuntLeaderboard.jsx +++ b/client/src/pages/ScuntLeaderboard/ScuntLeaderboard.jsx @@ -33,32 +33,32 @@ const ScuntLeaderboard = () => { socket.emit('getScores'); }); socket.on('scores', (scores) => { - setLeaderboard( - scores.map((team) => { - if (team.points < 0) { - team.points = 0; - } - return team; - }), - ); + // Sort the scores before setting the leaderboard state + const sortedScores = scores.map((team) => ({ + ...team, + points: team.points < 0 ? 0 : team.points + })).sort((a, b) => b.points - a.points); // Sort by points in descending order + + setLeaderboard(sortedScores); }); socket.on('update', (teamNumber, points) => { setLeaderboard((prevLeaderboard) => { - return prevLeaderboard.map((team) => { - if (team.number === teamNumber) { - team.points = points < 0 ? 0 : points; - } - return team; - }); + const updatedLeaderboard = prevLeaderboard.map((team) => ({ + ...team, + points: team.number === teamNumber ? Math.max(points, 0) : team.points + })); + // Sort again after updating + return updatedLeaderboard.sort((a, b) => b.points - a.points); }); }); - + return () => { socket.off('connect'); socket.off('scores'); socket.disconnect(); }; }, []); + useEffect(() => { if (scuntSettings) { @@ -130,17 +130,17 @@ const ScuntLeaderboardShow = ({ leaderboard }) => { - +
- +
- +
); @@ -192,7 +192,6 @@ const ScuntLeaderboardDesktop = ({ arr }) => { }; const ScuntLeaderboardMobile = ({ arr }) => { - arr.sort((a, b) => b.computedPoints - a.computedPoints); return (