From 0a7529dc07ae1eb5455efacdd3683e3a66dc35c4 Mon Sep 17 00:00:00 2001 From: 0xsysr3ll <0xsysr3ll@pm.me> Date: Tue, 17 Jun 2025 20:02:25 +0200 Subject: [PATCH] refactor(userlist): streamline user sorting logic and improve performance --- src/components/UserList/index.tsx | 70 ++++++++++++------------------- 1 file changed, 26 insertions(+), 44 deletions(-) diff --git a/src/components/UserList/index.tsx b/src/components/UserList/index.tsx index 67325dfe..c2afb1fe 100644 --- a/src/components/UserList/index.tsx +++ b/src/components/UserList/index.tsx @@ -127,48 +127,12 @@ const UserList = () => { }&sort=created&sortDirection=desc` ); - useEffect(() => { - if (data?.results) { - const sortedUsers = [...data.results].sort((a, b) => { - let comparison = 0; - switch (currentSort) { - case 'displayname': - comparison = a.displayName.localeCompare(b.displayName); - break; - case 'requests': - comparison = (a.requestCount ?? 0) - (b.requestCount ?? 0); - break; - case 'usertype': - comparison = a.userType - b.userType; - break; - case 'role': - comparison = a.permissions - b.permissions; - break; - case 'created': - comparison = - new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(); - break; - default: - comparison = 0; - } - return sortDirection === 'asc' ? comparison : -comparison; - }); - setLocalUsers(sortedUsers); - } - }, [data, currentSort, sortDirection]); - - const handleSortChange = (sortKey: Sort) => { - const newSortDirection = - currentSort === sortKey - ? sortDirection === 'asc' - ? 'desc' - : 'asc' - : 'desc'; - - setCurrentSort(sortKey); - setSortDirection(newSortDirection); - - const sortedUsers = [...localUsers].sort((a, b) => { + const sortUsers = ( + users: User[], + sortKey: Sort, + direction: SortDirection + ) => { + return [...users].sort((a, b) => { let comparison = 0; switch (sortKey) { case 'displayname': @@ -190,9 +154,27 @@ const UserList = () => { default: comparison = 0; } - return newSortDirection === 'asc' ? comparison : -comparison; + return direction === 'asc' ? comparison : -comparison; }); - setLocalUsers(sortedUsers); + }; + + useEffect(() => { + if (data?.results) { + setLocalUsers(sortUsers(data.results, currentSort, sortDirection)); + } + }, [data, currentSort, sortDirection]); + + const handleSortChange = (sortKey: Sort) => { + const newSortDirection = + currentSort === sortKey + ? sortDirection === 'asc' + ? 'desc' + : 'asc' + : 'desc'; + + setCurrentSort(sortKey); + setSortDirection(newSortDirection); + setLocalUsers(sortUsers(localUsers, sortKey, newSortDirection)); }; const [isDeleting, setDeleting] = useState(false);