idb-keyval

repository·main·Indexed 25 days ago

https://github.com/jakearchibald/idb-keyval

A lightweight, promise-based key-value store built on top of IndexedDB. Version 6.3.0 provides a simple API for storing structured-clonable data in the browser, featuring methods for basic operations (get, set, del, clear), batch operations (setMany, getMany, delMany), atomic updates via update(), and store iteration (entries, keys, values). It includes support for custom database and store names through createStore and offers a compat build for legacy environments like IE10/11.

Tokens
2.2K
Snippets
13
Records
24
Agent score
82%

What's inside idb-keyval

  1. Use idb-keyval in legacy environments (IE10/11)

    main

    If targeting older browsers like IE10/11, use the compat build and ensure you import a Promise polyfill.

    // Import a Promise polyfill
    import 'es6-promise/auto';
    import { get, set } from 'idb-keyval/compat';
  2. Define a custom database and store name with createStore

    main

    By default, idb-keyval uses the database name keyval-store and the store name keyval. To use different names, use the createStore function. This function returns a customStore object that can be passed as the final argument to all idb-keyval methods (like set, get, del, etc.).

    Limitations:

    • createStore cannot create multiple stores within the same database.
    • createStore cannot create a store within an existing database.
    • If you need to manage multiple stores in one database or handle complex schema migrations, use IDB on NPM instead.
    import { set, createStore } from 'idb-keyval';
    
    const customStore = createStore('custom-db-name', 'custom-store-name');
    
    set('hello', 'world', customStore);
  3. Use idb-keyval via CDN

    main

    You can load the library directly in the browser using jsDelivr.

    UMD (Legacy):

    <script src="https://cdn.jsdelivr.net/npm/idb-keyval@6/dist/umd.js"></script>

    ES Module (Modern):

    <script type="module">
      import { get, set } from 'https://cdn.jsdelivr.net/npm/idb-keyval@6/+esm';
    </script>
    <script src="https://cdn.jsdelivr.net/npm/idb-keyval@6/dist/umd.js"></script>
    <!-- Or in modern browsers: -->
    <script type="module">
      import { get, set } from 'https://cdn.jsdelivr.net/npm/idb-keyval@6/+esm';
    </script>
  4. Delete keys with del() and delMany()

    main
    • del(key): Deletes a specific key.
    • delMany(keys): Deletes multiple keys at once, which is more efficient than calling del multiple times.
    import { del, delMany } from 'idb-keyval';
    
    del('hello');
    
    delMany([123, 'hello'])
      .then(() => console.log('It worked!'))
      .catch((err) => console.log('It failed!', err));
  5. Atomic updates with update()

    main

    To avoid race conditions when transforming a value (e.g., incrementing a counter), use update(key, transformFn). This automatically queues updates so they are processed sequentially and safely.

    import { update } from 'idb-keyval';
    
    update('counter', (val) => (val || 0) + 1);
    update('counter', (val) => (val || 0) + 1);
  6. Retrieve values with get()

    main

    The get(key) method retrieves the value associated with the provided key. If the key does not exist, the promise resolves to undefined.

    import { get } from 'idb-keyval';
    
    // logs: "world"
    get('hello').then((val) => console.log(val));
  7. Iterate or list store contents with entries(), keys(), and values()

    main
    • entries(): Returns an array of all [key, value] pairs in the store.
    • keys(): Returns an array of all keys in the store.
    • values(): Returns an array of all values in the store.
    import { entries, keys, values } from 'idb-keyval';
    
    // logs: [[123, 456], ['hello', 'world']]
    entries().then((entries) => console.log(entries));
    
    // logs: [123, 'hello']
    keys().then((keys) => console.log(keys));
    
    // logs: [456, 'world']
    values().then((values) => console.log(values));
  8. Use createStore to define a custom store

    main

    The createStore(dbName, storeName) function creates a custom store configuration. The resulting object is a function that accepts a transaction mode ("readonly" or "readwrite") and a callback. The callback provides access to the IndexedDB object store.

    Note that because of how IndexedDB handles schema migrations, you cannot use createStore to target different stores within the same database name. Each createStore call with a unique dbName is valid, but multiple calls with the same dbName but different storeName will not work as expected.

    import { promisifyRequest } from 'idb-keyval';
    
    function createStore(dbName, storeName) {
      const request = indexedDB.open(dbName);
      request.onupgradeneeded = () => request.result.createObjectStore(storeName);
      const dbp = promisifyRequest(request);
    
      return (txMode, callback) =>
        dbp.then((db) =>
          callback(db.transaction(storeName, txMode).objectStore(storeName)),
        );
    }
  9. Batch operations with setMany() and getMany()

    main

    Use setMany and getMany for better performance when dealing with multiple keys.

    • setMany(entries): Takes an array of [key, value] pairs. This operation is atomic; if one pair fails, none are added.
    • getMany(keys): Takes an array of keys and resolves with an array of values.