78 lines
2.0 KiB
TypeScript
78 lines
2.0 KiB
TypeScript
"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 refreshSilent = useCallback(async () => {
|
|
try {
|
|
const fetchedData = await loadData();
|
|
setData(fetchedData);
|
|
} catch (err) {
|
|
console.error("Error silently refreshing banking data:", err);
|
|
}
|
|
}, []);
|
|
|
|
const update = useCallback((newData: BankingData) => {
|
|
// Optimistic update - the actual save happens in individual operations
|
|
setData(newData);
|
|
}, []);
|
|
|
|
return { data, isLoading, error, refresh, refreshSilent, 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;
|
|
}
|