From b199b850b1c92db111a6ef5df5b2be763d91d782 Mon Sep 17 00:00:00 2001 From: Melanie Matthews Date: Thu, 7 Nov 2024 17:12:12 +1100 Subject: [PATCH] feat: sort categories and subcategories --- app/javascript/hooks/useGroupedCategories.ts | 46 ++++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/app/javascript/hooks/useGroupedCategories.ts b/app/javascript/hooks/useGroupedCategories.ts index 82d8d01..d7f4717 100644 --- a/app/javascript/hooks/useGroupedCategories.ts +++ b/app/javascript/hooks/useGroupedCategories.ts @@ -26,6 +26,22 @@ type UseGroupedCategories = { currentSubcategory?: Subcategory } +const sortFn = ( + a: Category | Subcategory, + b: Category | Subcategory, +): number => { + const nameA = a.name.toUpperCase() + const nameB = b.name.toUpperCase() + if (nameA < nameB) { + return -1 + } + if (nameA > nameB) { + return 1 + } + + return 0 +} + export const useGroupedCategories = (): UseGroupedCategories => { const { data: categories, @@ -53,20 +69,22 @@ export const useGroupedCategories = (): UseGroupedCategories => { const isSuccess = isSuccessC && isSuccessS && isSuccessT const groupedCategories = categoryTypes - ? categoryTypes - .map((ct) => ({ - categoryType: ct, - categories: categories - ? categories - .filter((c) => c.categoryTypeId == ct.id) - .map((c) => ({ - ...c, - subcategories: subcategories - ? subcategories?.filter((s) => s.categoryId == c.id) - : [], - })) - : [], - })) + ? categoryTypes.map((ct) => ({ + categoryType: ct, + categories: categories + ? categories + .filter((c) => c.categoryTypeId == ct.id) + .sort(sortFn) + .map((c) => ({ + ...c, + subcategories: subcategories + ? subcategories + ?.filter((s) => s.categoryId == c.id) + .sort(sortFn) + : [], + })) + : [], + })) : [] return {