From b2b49909936dc9c5ef77e843d98a87f3e3894861 Mon Sep 17 00:00:00 2001
From: Rosyid Haryadi <rosyid_haryadi@protonmail.com>
Date: Mon, 2 Oct 2023 23:05:59 +0700
Subject: simplifying fetch but cursed useeffect always fired twice in dev
 environment and doesn't respect state, i hate this.

---
 src/Result.jsx | 30 ++++++++++++++++++------------
 1 file changed, 18 insertions(+), 12 deletions(-)

(limited to 'src/Result.jsx')

diff --git a/src/Result.jsx b/src/Result.jsx
index 374298d..f014c78 100644
--- a/src/Result.jsx
+++ b/src/Result.jsx
@@ -5,16 +5,30 @@ import dayjs from "dayjs";
 
 function Result({listEntry, baseSalary}) {
     const [totalOvertimePay, setTotalOvertimePay] = useState(0);
-    const [holidayData, setHolidayData] = useState(null);
+    const [holidayData, setHolidayData] = useState([[]]);
+    const [fetched, setFetched] = useState([]);
+
 
     useEffect(() => {
         setTotalOvertimePay(getOvertimePayTotal(listEntry, baseSalary, holidayData));
     }, [listEntry, baseSalary, holidayData]);
 
+    const fetchApi = (year) => {
+        const baseUrl = 'https://dayoffapi.vercel.app/api';
+        if (fetched.includes(year)) {
+            return Promise.resolve();
+        }
+        return fetch(`${baseUrl}/?year=${year}`)
+            .then((response) => response.json())
+            .then((data) => {
+                setHolidayData((currentData) => [...currentData, ...data]);
+                setFetched((current) => [...current, year]);
+            });
+    }
+
     useEffect(() => {
-        fetchApi(dayjs().year()).then((result) => {
-            setHolidayData(result);
-        })
+        fetchApi(dayjs().year()).then(() => {});
+        fetchApi(dayjs().year() - 1).then(() => {});
     }, []);
 
     if (totalOvertimePay < 0) {
@@ -48,14 +62,6 @@ function Result({listEntry, baseSalary}) {
     )
 }
 
-function fetchApi(year) {
-    // kemungkinan nanti ada pengecekan taun udah pernah difetch / belum
-    const baseUrl = 'https://dayoffapi.vercel.app/api';
-    return fetch(`${baseUrl}/?year=${year}`)
-        .then((response) => response.json())
-        .then((data) => data);
-}
-
 function segmentTime(duration, segments) {
     const segmentedHours = [];
 
-- 
cgit v1.2.3-70-g09d2

