Spaces:
Sleeping
Sleeping
File size: 1,543 Bytes
1fff71f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | // localStorage wrapper with type-safe getters/setters
/**
* Get item from localStorage with JSON parsing
* @param key Storage key
* @returns Parsed value or null if not found
*/
export function getItem<T>(key: string): T | null {
try {
const item = localStorage.getItem(key);
if (item === null) {
return null;
}
return JSON.parse(item) as T;
} catch (error) {
console.error(`Error reading from localStorage (${key}):`, error);
return null;
}
}
/**
* Set item in localStorage with JSON stringification
* @param key Storage key
* @param value Value to store
*/
export function setItem<T>(key: string, value: T): void {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error writing to localStorage (${key}):`, error);
}
}
/**
* Remove item from localStorage
* @param key Storage key
*/
export function removeItem(key: string): void {
try {
localStorage.removeItem(key);
} catch (error) {
console.error(`Error removing from localStorage (${key}):`, error);
}
}
/**
* Clear all items from localStorage
*/
export function clear(): void {
try {
localStorage.clear();
} catch (error) {
console.error('Error clearing localStorage:', error);
}
}
/**
* Check if localStorage is available
* @returns True if localStorage is available, false otherwise
*/
export function isAvailable(): boolean {
try {
const test = '__storage_test__';
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch {
return false;
}
}
|