Files
kandev/apps/web/lib/local-storage.ts
T
2026-01-10 23:17:26 +00:00

31 lines
873 B
TypeScript

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
export function getLocalStorage<T extends JsonValue>(key: string, fallback: T): T {
if (typeof window === 'undefined') return fallback;
try {
const raw = window.localStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
export function setLocalStorage<T extends JsonValue>(key: string, value: T): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// Ignore write failures (storage full, blocked, etc.)
}
}
export function removeLocalStorage(key: string): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.removeItem(key);
} catch {
// Ignore removal failures.
}
}