From f09a72f90c049b5e1a8478f737062a24d9c7a3df Mon Sep 17 00:00:00 2001
From: trisusilo48 <tri.susilo@altama.co.id>
Date: Tue, 8 Oct 2024 14:56:00 +0700
Subject: cache localstorage

---
 src-migrate/modules/page-content/index.tsx | 30 +++++++++++++++++++++++++-----
 1 file changed, 25 insertions(+), 5 deletions(-)

(limited to 'src-migrate/modules/page-content/index.tsx')

diff --git a/src-migrate/modules/page-content/index.tsx b/src-migrate/modules/page-content/index.tsx
index edecb855..3423ca8b 100644
--- a/src-migrate/modules/page-content/index.tsx
+++ b/src-migrate/modules/page-content/index.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from 'react';
+import { useEffect, useMemo, useState } from 'react';
 import { useQuery } from 'react-query';
 import { PageContentProps } from '~/types/pageContent';
 import { getPageContent } from '~/services/pageContent';
@@ -8,18 +8,38 @@ type Props = {
 };
 
 const PageContent = ({ path }: Props) => {
+  const [localData, setData] = useState<PageContentProps>();
+  const [shouldFetch, setShouldFetch] = useState(false);
+
+  useEffect(() => {
+    const localData = localStorage.getItem(`page-content:${path}`);
+    if (localData) {
+      setData(JSON.parse(localData));
+    }else{
+      setShouldFetch(true);
+    }
+  },[])
+  
   const { data, isLoading } = useQuery<PageContentProps>(
     `page-content:${path}`,
-    async () => await getPageContent({ path })
+    async () => await getPageContent({ path }), {
+      enabled: shouldFetch,
+      onSuccess: (data) => {
+        if (data) {
+          localStorage.setItem(`page-content:${path}`, JSON.stringify(data));
+          setData(data);
+        }
+      },
+    }
   );
 
   const parsedContent = useMemo<string>(() => {
-    if (!data) return '';
-    return data.content.replaceAll(
+    if (!localData) return '';
+    return localData.content.replaceAll(
       'src="/web/image',
       `src="${process.env.NEXT_PUBLIC_ODOO_API_HOST}/web/image`
     );
-  }, [data]);
+  }, [localData]);
   if (isLoading) return <PageContentSkeleton />;
 
   return <div dangerouslySetInnerHTML={{ __html: parsedContent || '' }}></div>;
-- 
cgit v1.2.3

