npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@asaidimu/browser-store

v1.0.1

Published

A simple wrapper around localstorage and session storage

Downloads

128

Readme

@asaidimu/browser-store

TypeScript Local Storage Manager

MIT License TypeScript

A type-safe, robust wrapper around browser's Storage API with cross-tab synchronization support. Built with TypeScript for maximum type safety and developer experience.

✨ Features

  • 🔒 Type-safe: Full TypeScript support with precise type inference
  • 🔄 Cross-tab synchronization: Real-time updates across browser tabs
  • 🎯 Namespacing: Prefix support to avoid key collisions
  • 🧹 Memory efficient: Automatic cleanup of event listeners
  • 🛡️ Error handling: Graceful handling of storage quota and parsing errors
  • 💪 Flexible: Works with both localStorage and sessionStorage

📦 Installation

npm install @asaidimu/browser-store
# or
yarn add @asaidimu/browser-store
# or
pnpm add @asaidimu/browser-store

🚀 Quick Start

import createLocalStore from '@asaidimu/browser-store';

// Define your store structure
interface MyStore {
  user: {
    name: string;
    age: number;
  };
  settings: {
    theme: 'light' | 'dark';
    notifications: boolean;
  };
}

// Create a store instance
const store = createLocalStore<MyStore>({
  prefix: 'myApp:', // Optional prefix for all keys
});

// Set values
store.set('user', { 
  name: 'John Doe', 
  age: 30 
});

// Partial updates
store.update('user', { 
  age: 31  // Only updates age, preserves name
});

// Get values
const user = store.get('user');
console.log(user?.name); // "John Doe"

// Listen for changes (including from other tabs)
const cleanup = store.onChange('settings', (current, previous) => {
  console.log('Settings changed:', { current, previous });
});

// Remove specific key
store.clear('user');

// Clear all data with prefix
store.clearAll();

// Clean up listeners when done
cleanup();

📖 API Reference

createLocalStore<T>(options?: StoreOptions): LocalStore<T>

Creates a new store instance.

Options

interface StoreOptions {
  storage?: Storage;        // defaults to localStorage
  prefix?: string;         // namespace prefix for keys
}

Methods

  • set<K>(key: K, value: T[K]): void
    Sets a value for a key, replacing any existing value.

  • update<K>(key: K, value: Partial<T[K]>): void
    Partially updates an existing value, preserving unspecified fields.

  • get<K>(key: K): T[K] | null
    Retrieves a value by key. Returns null if not found.

  • clear<K>(key: K): void
    Removes a specific key and its value.

  • clearAll(): void
    Removes all values with the store's prefix.

  • onChange<K>(key: K, callback: (current: T[K] | null, previous?: T[K] | null) => void): () => void
    Subscribes to changes for a specific key. Returns a cleanup function.

🔥 Advanced Usage

Cross-Tab Communication

// Tab 1
const store = createLocalStore<MyStore>({ prefix: 'myApp:' });
store.onChange('settings', (current) => {
  console.log('Settings updated in another tab:', current);
});

// Tab 2
const store2 = createLocalStore<MyStore>({ prefix: 'myApp:' });
store2.set('settings', { theme: 'dark', notifications: true });
// Tab 1 will log the new settings

Using with SessionStorage

const sessionStore = createLocalStore<MyStore>({
  storage: window.sessionStorage,
  prefix: 'myApp:',
});

Type-Safe Partial Updates

interface User {
  name: string;
  age: number;
  preferences: {
    newsletter: boolean;
    theme: string;
  };
}

interface MyStore {
  user: User;
}

const store = createLocalStore<MyStore>();

// This will error if fields don't match User type
store.update('user', {
  age: 32,
  preferences: {
    newsletter: true,
  },
});

⚠️ Error Handling

The library handles common errors gracefully:

  • Storage quota exceeded
  • JSON parsing errors
  • Invalid data types
  • Missing keys
try {
  store.set('user', { /* large data */ });
} catch (error) {
  if (error instanceof Error) {
    console.error('Storage operation failed:', error.message);
  }
}

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.