diff --git a/src/constants/storage-keys.ts b/src/constants/storage-keys.ts new file mode 100644 index 0000000..cddcf78 --- /dev/null +++ b/src/constants/storage-keys.ts @@ -0,0 +1,3 @@ +export const STORAGE_KEYS = { + RESULTS: 'monash-grades-calculator:results' +} as const diff --git a/src/hooks/use-local-storage.ts b/src/hooks/use-local-storage.ts new file mode 100644 index 0000000..2704e8f --- /dev/null +++ b/src/hooks/use-local-storage.ts @@ -0,0 +1,25 @@ +import { useState, useEffect } from 'react' + +export function useLocalStorage(key: string, initialValue: T) { + // Initialize state with stored value or initial value + const [value, setValue] = useState(() => { + try { + const item = window.localStorage.getItem(key) + return item ? JSON.parse(item) : initialValue + } catch (error) { + console.warn(`Error reading localStorage key "${key}":`, error) + return initialValue + } + }) + + // Update localStorage when state changes + useEffect(() => { + try { + window.localStorage.setItem(key, JSON.stringify(value)) + } catch (error) { + console.warn(`Error setting localStorage key "${key}":`, error) + } + }, [key, value]) + + return [value, setValue] as const +} diff --git a/src/routes/index.lazy.tsx b/src/routes/index.lazy.tsx index a28b16c..8daf3db 100644 --- a/src/routes/index.lazy.tsx +++ b/src/routes/index.lazy.tsx @@ -1,5 +1,6 @@ import { createLazyFileRoute } from '@tanstack/react-router' -import { useState } from 'react' +import { useLocalStorage } from '@/hooks/use-local-storage' +import { STORAGE_KEYS } from '@/constants/storage-keys' import { useTheme } from "@/components/theme/theme-provider" import { calculateWAM, calculateGPA, calculateColor } from "@/lib/calculate" import { Result } from "@/schemas/result-schema" @@ -86,7 +87,7 @@ function StatCard({ title, subtitle, value, maxValue }: StatCardProps) { } function Index() { - const [data, setData] = useState(initialData) + const [data, setData] = useLocalStorage(STORAGE_KEYS.RESULTS, initialData) const handleResultAdd = () => { const maxId = Math.max(...data.map(item => item.id), -1) @@ -97,17 +98,17 @@ function Index() { mark: 0, grade: "N", } - setData(prevData => [...prevData, newResult]) + setData([...data, newResult]) } const handleResultUpdate = (id: number, updatedResult: Result) => { - setData(prevData => prevData.map(item => + setData(data.map(item => item.id === id ? { ...updatedResult, id } : item )) } const handleResultDelete = (id: number) => { - setData(prevData => prevData.filter(item => item.id !== id)) + setData(data.filter(item => item.id !== id)) } const wam = calculateWAM(data)