From 97ca61180abe29a4fb345d5891fd0b3e342bbcd8 Mon Sep 17 00:00:00 2001
From: Rithvik Nishad <mail@rithviknishad.dev>
Date: Mon, 25 Dec 2023 16:11:47 +0530
Subject: [PATCH] Fixes Filters Cache restore logic (#6908)

* Fixes Filters Cache restore logic

* remove cache

---------

Co-authored-by: Mohammed Nihal <57055998+nihal467@users.noreply.github.com>
---
 .../e2e/facility_spec/facility_creation.cy.ts |  1 -
 src/Common/hooks/useFilters.tsx               | 59 ++++++++++++-------
 2 files changed, 39 insertions(+), 21 deletions(-)

diff --git a/cypress/e2e/facility_spec/facility_creation.cy.ts b/cypress/e2e/facility_spec/facility_creation.cy.ts
index 9725ed42a28..f8001584ac3 100644
--- a/cypress/e2e/facility_spec/facility_creation.cy.ts
+++ b/cypress/e2e/facility_spec/facility_creation.cy.ts
@@ -221,7 +221,6 @@ describe("Facility Creation", () => {
       .should("be.visible");
     // verify the facility homepage
     cy.visit("/facility");
-    cy.get("#removeicon").click();
     manageUserPage.typeFacilitySearch(facilityName);
     facilityPage.verifyFacilityBadgeContent(facilityName);
     manageUserPage.assertFacilityInCard(facilityName);
diff --git a/src/Common/hooks/useFilters.tsx b/src/Common/hooks/useFilters.tsx
index a62180c8a29..5781eaca54f 100644
--- a/src/Common/hooks/useFilters.tsx
+++ b/src/Common/hooks/useFilters.tsx
@@ -33,28 +33,24 @@ export default function useFilters({ limit = 14 }: { limit?: number }) {
     if (!hasPagination) return;
     setQueryParams(Object.assign({}, qParams, { page }), { replace: true });
   };
-  const removeFilter = (param: string) => updateQuery({ [param]: "" });
-  const removeFilters = (keys: string[]) =>
-    updateQuery(keys.reduce((acc, key) => ({ ...acc, [key]: "" }), qParams));
+  const removeFilters = (params: string[]) => {
+    setQueryParams(removeFromQuery(qParams, params));
+  };
+  const removeFilter = (param: string) => removeFilters([param]);
 
-  useEffect(() => {
-    const localFilters = JSON.parse(
-      localStorage.getItem("filters--" + window.location.pathname) || "{}"
-    );
-    const blacklistLocalFilters = ["page", "limit", "offset"];
-    const newFilters = { ...localFilters, ...qParams };
-    const filteredNewFilters = blacklistLocalFilters.reduce(
-      (acc, key) => ({ ...acc, [key]: undefined }),
-      newFilters
-    );
+  useEffect(() => updateFiltersCache(qParams), [qParams]);
 
-    localStorage.setItem(
-      "filters--" + window.location.pathname,
-      JSON.stringify(filteredNewFilters)
+  useEffect(() => {
+    const cache = getFiltersCache();
+    const qParamKeys = Object.keys(qParams);
+    const canSkip = Object.keys(cache).every(
+      (key) => qParamKeys.includes(key) && qParams[key] === cache[key]
     );
-
-    updateQuery(newFilters);
-  }, [qParams]);
+    if (canSkip) return;
+    if (Object.keys(cache).length) {
+      setQueryParams(cache);
+    }
+  }, []);
 
   const FilterBadge = ({ name, value, paramKey }: FilterBadgeProps) => {
     if (Array.isArray(paramKey))
@@ -174,7 +170,8 @@ export default function useFilters({ limit = 14 }: { limit?: number }) {
             id="clear-all-filters"
             className="rounded-full border border-gray-300 bg-white px-2 py-1 text-xs text-gray-600 hover:text-gray-800"
             onClick={() => {
-              removeFilters(activeFilters);
+              updateFiltersCache({});
+              removeFilters(Object.keys(qParams));
             }}
           >
             {t("clear_all_filters")}
@@ -254,3 +251,25 @@ export default function useFilters({ limit = 14 }: { limit?: number }) {
     },
   };
 }
+
+const removeFromQuery = (query: Record<string, unknown>, params: string[]) => {
+  const result = { ...query };
+  for (const param of params) {
+    delete result[param];
+  }
+  return result;
+};
+
+const FILTERS_CACHE_BLACKLIST = ["page", "limit", "offset"];
+
+const getFiltersCacheKey = () => `filters--${window.location.pathname}`;
+const getFiltersCache = () => {
+  return JSON.parse(localStorage.getItem(getFiltersCacheKey()) || "{}");
+};
+const updateFiltersCache = (cache: Record<string, unknown>) => {
+  const result = { ...cache };
+  for (const param of FILTERS_CACHE_BLACKLIST) {
+    delete result[param];
+  }
+  localStorage.setItem(getFiltersCacheKey(), JSON.stringify(result));
+};