1.0.2 โข Published 6 months ago
@milandadhaniya/local-storage-hook v1.0.2
@milandadhaniya/local-storage-hook
A simple and typed utility for interacting with localStorage in the browser using TypeScript. Built-in support for structured key-value storage, nested field manipulation, custom event dispatching, and optional logging using @milandadhaniya/tiny-logger-js.
๐ฆ Installation
npm install @milandadhaniya/local-storage-hook๐ API
import {
setItem,
getItem,
removeItem,
clearStorage
} from '@milandadhaniya/local-storage-hook';๐งช Usage Examples
โ
setItem
Sets a value in localStorage. Returns true if successful, false otherwise.
// Set a raw value
setItem('AppSettings', null, {
themeOptions: ['dark', 'light'],
language: 'en',
notifications: {
enabled: true,
sound: true,
vibration: false
},
font: {
family: 'Arial'
}
});
// Set an object field
setItem('AppSettings', 'font', {
size: '16px',
family: 'Arial'
});
// Enable logging (Default: false)
setItem('SelectedTheme', null, 'dark', true);๐ฅ getItem
Retrieves a value from localStorage. Returns the requested value or undefined if not found.
// Get the raw value
const raw = getItem('AppSettings');
// Get nested field from object
const notifications = getItem('AppSettings', 'notifications');๐๏ธ removeItem
Removes an item from localStorage. Returns true if successful, false otherwise.
// Remove specific field from an object (Enable logging)
removeItem('AppSettings', 'font', true);
// Remove the full key
removeItem('AppSettings');๐งน clearStorage
Clears all items from localStorage. Returns true if successful, false otherwise.
// Clear everything
clearStorage();
// With logging
clearStorage(true);๐ง Listen for Changes
const handler = (e: CustomEvent) => {
console.log('Storage event fired:', e.detail);
};
window.addEventListener('local-storage-change', handler);
// Later, to clean up
window.removeEventListener('local-storage-change', handler);๐ License
MIT License โ ยฉ 2025 Milan Dadhaniya