1.0.2 โ€ข Published 6 months ago

@milandadhaniya/local-storage-hook v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

@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

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago