chore: init from v0
This commit is contained in:
67
lib/hooks.ts
Normal file
67
lib/hooks.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
import type { BankingData } from "./types"
|
||||
import { loadData } from "./store-db"
|
||||
|
||||
export function useBankingData() {
|
||||
const [data, setData] = useState<BankingData | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<Error | null>(null)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
const fetchedData = await loadData()
|
||||
setData(fetchedData)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err : new Error("Failed to load data"))
|
||||
console.error("Error loading banking data:", err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const update = useCallback((newData: BankingData) => {
|
||||
// Optimistic update - the actual save happens in individual operations
|
||||
setData(newData)
|
||||
}, [])
|
||||
|
||||
return { data, isLoading, error, refresh, update }
|
||||
}
|
||||
|
||||
export function useLocalStorage<T>(key: string, initialValue: T) {
|
||||
const [storedValue, setStoredValue] = useState<T>(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const item = window.localStorage.getItem(key)
|
||||
if (item) {
|
||||
setStoredValue(JSON.parse(item))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}, [key])
|
||||
|
||||
const setValue = (value: T | ((val: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(storedValue) : value
|
||||
setStoredValue(valueToStore)
|
||||
window.localStorage.setItem(key, JSON.stringify(valueToStore))
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
return [storedValue, setValue] as const
|
||||
}
|
||||
Reference in New Issue
Block a user