38 lines
740 B
TypeScript
38 lines
740 B
TypeScript
export function safeGetItem(key: string): string | null {
|
|
try {
|
|
return localStorage.getItem(key);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function safeSetItem(key: string, value: string): void {
|
|
try {
|
|
localStorage.setItem(key, value);
|
|
} catch {
|
|
// ignore quota / private mode
|
|
}
|
|
}
|
|
|
|
export function safeRemoveItem(key: string): void {
|
|
try {
|
|
localStorage.removeItem(key);
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|
|
|
|
export function readJson<T>(key: string, fallback: T): T {
|
|
const raw = safeGetItem(key);
|
|
if (!raw) return fallback;
|
|
try {
|
|
return JSON.parse(raw) as T;
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
export function writeJson(key: string, value: unknown): void {
|
|
safeSetItem(key, JSON.stringify(value));
|
|
}
|