From e8e7275a25939bfaeacaf2a9cbf508b514647057 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 8 Oct 2024 10:31:13 +0700
Subject: <iman> update category management to storage on local

---
 src/lib/home/components/CategoryDynamicMobile.jsx | 111 ++++++++++++++++------
 1 file changed, 82 insertions(+), 29 deletions(-)

(limited to 'src/lib/home/components/CategoryDynamicMobile.jsx')

diff --git a/src/lib/home/components/CategoryDynamicMobile.jsx b/src/lib/home/components/CategoryDynamicMobile.jsx
index 4a8f13cf..075e9444 100644
--- a/src/lib/home/components/CategoryDynamicMobile.jsx
+++ b/src/lib/home/components/CategoryDynamicMobile.jsx
@@ -4,52 +4,105 @@ import Link from 'next/link';
 import { createSlug } from '@/core/utils/slug';
 import { Swiper, SwiperSlide } from 'swiper/react';
 import 'swiper/css';
-import { fetchCategoryManagementSolr } from '../api/categoryManagementApi';
+import {
+  fetchCategoryManagementSolr,
+  fetchCategoryManagementVersion,
+} from '../api/categoryManagementApi';
+
+const saveToLocalStorage = (key, data, version, expiryInHours) => {
+  const now = new Date();
+  const item = {
+    value: data,
+    version: version,
+    expiry: now.getTime() + expiryInHours * 60 * 60 * 1000,
+  };
+  localStorage.setItem(key, JSON.stringify(item));
+};
+
+const getFromLocalStorage = (key) => {
+  const itemStr = localStorage.getItem(key);
+  if (!itemStr) return null;
+
+  const item = JSON.parse(itemStr);
+  const now = new Date();
+
+  if (now.getTime() > item.expiry) {
+    localStorage.removeItem(key);
+    return null;
+  }
+
+  return item;
+};
+
+const isExpired = (expiry) => {
+  const now = new Date();
+  return now.getTime() > expiry;
+};
 
 const CategoryDynamicMobile = () => {
   const [selectedCategory, setSelectedCategory] = useState({});
   const [categoryManagement, setCategoryManagement] = useState([]);
   const [isLoading, setIsLoading] = useState(false);
 
-  const loadBrand = useCallback(async () => {
-    setIsLoading(true);
-    const items = await fetchCategoryManagementSolr();
+  const loadCategoryManagement = useCallback(async () => {
+    const cachedData = getFromLocalStorage('homepage_categoryDynamic'); // nama key namaPage_namaKomopnen
+    const cachedVersion = cachedData?.version;
+    // apakah data sudah kadaluarsa
+    const dataExpired = cachedData ? isExpired(cachedData.expiry) : true;
+
+    if (cachedData && !dataExpired) {
+      setCategoryManagement(cachedData.value);
+    } else {
+      // Jika kadaluarsa, cek versi terbaru dari API
+      const latestVersion = await fetchCategoryManagementVersion();
+
+      if (cachedData && cachedData.version === latestVersion) {
+        // Jika versinya sama, reset expiry
+        saveToLocalStorage(
+          'homepage_categoryDynamic',
+          cachedData.value,
+          latestVersion,
+          24
+        );
+        setCategoryManagement(cachedData.value);
+      } else {
+        // Jika versinya beda, lakukan fetch data baru
+        setIsLoading(true);
+        const items = await fetchCategoryManagementSolr();
+        setIsLoading(false);
 
-    setIsLoading(false);
-    setCategoryManagement(items);
+        // Simpan data baru
+        saveToLocalStorage(
+          'homepage_categoryDynamic',
+          items,
+          latestVersion,
+          24
+        );
+        setCategoryManagement(items);
+      }
+    }
   }, []);
 
   useEffect(() => {
-    loadBrand();
-  }, [loadBrand]);
+    loadCategoryManagement();
+  }, [loadCategoryManagement]);
 
   useEffect(() => {
-    const loadPromo = async () => {
-      try {
-        if (categoryManagement?.length > 0) {
-          const initialSelections = categoryManagement.reduce(
-            (acc, category) => {
-              if (category.categories.length > 0) {
-                acc[category.id] = category.categories[0].id_level_2;
-              }
-              return acc;
-            },
-            {}
-          );
-          setSelectedCategory(initialSelections);
+    if (categoryManagement?.length > 0) {
+      const initialSelections = categoryManagement.reduce((acc, category) => {
+        if (category.categories.length > 0) {
+          acc[category.id] = category.categories[0].id_level_2;
         }
-      } catch (loadError) {
-        // console.error("Error loading promo items:", loadError);
-      }
-    };
-
-    loadPromo();
+        return acc;
+      }, {});
+      setSelectedCategory(initialSelections);
+    }
   }, [categoryManagement]);
 
-  const handleCategoryLevel2Click = (categoryIdI, idLevel2) => {
+  const handleCategoryLevel2Click = (categoryId, idLevel2) => {
     setSelectedCategory((prev) => ({
       ...prev,
-      [categoryIdI]: idLevel2,
+      [categoryId]: idLevel2,
     }));
   };
 
-- 
cgit v1.2.3

