From 3ba09bc46f418cdc34d72fa0b31886b96015648a Mon Sep 17 00:00:00 2001 From: ImJustChew Date: Sun, 29 Oct 2023 22:14:37 +0800 Subject: [PATCH] changed userTimetable caching to use useSWR instead --- src/hooks/useUserTimetable.tsx | 45 ++++++++++++++-------------------- 1 file changed, 19 insertions(+), 26 deletions(-) diff --git a/src/hooks/useUserTimetable.tsx b/src/hooks/useUserTimetable.tsx index 839bfb8e..0932f001 100644 --- a/src/hooks/useUserTimetable.tsx +++ b/src/hooks/useUserTimetable.tsx @@ -1,41 +1,34 @@ -import { useLocalStorage } from "usehooks-ts"; import { useSettings } from "./contexts/settings"; import { useState, useEffect } from "react"; import supabase, { CourseDefinition } from "@/config/supabase"; import { createTimetableFromCourses } from "@/helpers/timetable"; import { CourseTimeslotData } from "@/types/timetable"; +import useSWR from "swr"; const useUserTimetable = (loadCourse = true) => { const { courses, timetableTheme, setCourses } = useSettings(); - const [localCourseCache, setLocalCourseCache] = useLocalStorage("cached_courses", []); + + const { data: allCourseData = [], error, isLoading } = useSWR(['courses', courses], async ([table, courseCodes]) => { + const { data = [], error } = await supabase.from('courses').select("*").in('raw_id', courseCodes); + if(error) throw error; + if(!data) throw new Error('No data'); + return data; + }); const [timetableData, setTimetableData] = useState([]); - const [allCourseData, setAllCourseData] = useState([]); useEffect(() => { if(!loadCourse) return; - console.info('Loading from Cache') - setAllCourseData(localCourseCache!); - setTimetableData(createTimetableFromCourses(localCourseCache, timetableTheme)); - }, []); - - useEffect(() => { - if(!loadCourse) return; - console.info('Loading from Server'); - (async () => { - try { - let { data = [], error } = await supabase.from('courses').select("*").in('raw_id', courses); - if(error) console.error(error); - else { - setAllCourseData(data!); - setTimetableData(createTimetableFromCourses(data!, timetableTheme)); - setLocalCourseCache(data!); - } - } catch(e) { - console.error(e); - } - })(); - }, [courses.length]) + if(error) { + console.error(error); + return; + } + if(isLoading) { + console.log('loading') + return; + } + setTimetableData(createTimetableFromCourses(allCourseData!, timetableTheme)); + }, [allCourseData, isLoading, error, timetableTheme]); const deleteCourse = async (course: CourseDefinition) => { setCourses(courses.filter(c => c != course.raw_id)); @@ -45,7 +38,7 @@ const useUserTimetable = (loadCourse = true) => { setCourses([...courses, course.raw_id!]); } - return { timetableData, allCourseData, deleteCourse, addCourse }; + return { timetableData, allCourseData, deleteCourse, addCourse, isLoading, error }; } export default useUserTimetable;