Skip to content

Commit

Permalink
make data persist in local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
ligsnf committed Dec 8, 2024
1 parent 4d08228 commit a2f5aba
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
3 changes: 3 additions & 0 deletions src/constants/storage-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const STORAGE_KEYS = {
RESULTS: 'monash-grades-calculator:results'
} as const
25 changes: 25 additions & 0 deletions src/hooks/use-local-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useState, useEffect } from 'react'

export function useLocalStorage<T>(key: string, initialValue: T) {
// Initialize state with stored value or initial value
const [value, setValue] = useState<T>(() => {
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
}
11 changes: 6 additions & 5 deletions src/routes/index.lazy.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -86,7 +87,7 @@ function StatCard({ title, subtitle, value, maxValue }: StatCardProps) {
}

function Index() {
const [data, setData] = useState<Result[]>(initialData)
const [data, setData] = useLocalStorage<Result[]>(STORAGE_KEYS.RESULTS, initialData)

const handleResultAdd = () => {
const maxId = Math.max(...data.map(item => item.id), -1)
Expand All @@ -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)
Expand Down

0 comments on commit a2f5aba

Please sign in to comment.