Christian Kniep
new webapp
1fff71f
// 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;
}
}