Skip to content

Commit

Permalink
changed userTimetable caching to use useSWR instead
Browse files Browse the repository at this point in the history
  • Loading branch information
ImJustChew committed Oct 29, 2023
1 parent 349689e commit 3ba09bc
Showing 1 changed file with 19 additions and 26 deletions.
45 changes: 19 additions & 26 deletions src/hooks/useUserTimetable.tsx
Original file line number Diff line number Diff line change
@@ -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<CourseDefinition[]>("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<CourseTimeslotData[]>([]);
const [allCourseData, setAllCourseData] = useState<CourseDefinition[]>([]);

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));
Expand All @@ -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;
Expand Down

0 comments on commit 3ba09bc

Please sign in to comment.