Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

addToIndexedDB

Adds a record to an object store in IndexedDB.

TypeScript
Copied!
1/**
2 * Adds a record to an object store in IndexedDB.
3 *
4 * @param db - The open IDBDatabase instance.
5 * @param storeName - The name of the object store.
6 * @param data - The data to add.
7 * @returns A Promise that resolves with the inserted key.
8 */
9export function addToIndexedDB<T = any>(
10  db: IDBDatabase,
11  storeName: string,
12  data: T
13): Promise<IDBValidKey> {
14  return new Promise((resolve, reject) => {
15    const transaction = db.transaction([storeName], 'readwrite');
16    const store = transaction.objectStore(storeName);
17    const request = store.add(data);
18
19    request.onsuccess = () => resolve(request.result);
20    request.onerror = () => reject(request.error);
21  });
22}
  • Typed Data Insertion

    Supports generic typing with <T>, offering type safety and flexibility for diverse record structures.

  • Promise-Based Flow

    Wraps the native IndexedDB request in a Promise, making the API cleaner and easier to use with async/await syntax.

  • Isolated Transaction Scope

    Encapsulates each insert operation in a dedicated readwrite transaction, reducing the risk of side effects or locking issues.

  • Automatic Key Retrieval

    Resolves with the generated or provided key, which is useful for tracking newly inserted records without extra queries.

Tests | Examples

TypeScript
Copied!
1import { openIndexedDB } from './openIndexedDB';
2
3test('addToIndexedDB - adds a record and returns a key', async () => {
4  const db = await openIndexedDB('TestDB_Add', 1, {
5    upgrade(db) {
6      if (!db.objectStoreNames.contains('items')) {
7        db.createObjectStore('items', { keyPath: 'id' });
8      }
9    }
10  });
11
12  const result = await addToIndexedDB(db, 'items', { id: 1, name: 'Item 1' });
13
14  expect(result).toBe(1);
15  db.close();
16});
17
18test('addToIndexedDB - fails on invalid store', async () => {
19  const db = await openIndexedDB('TestDB_AddFail', 1, {
20    upgrade(db) {
21      if (!db.objectStoreNames.contains('valid')) {
22        db.createObjectStore('valid', { keyPath: 'id' });
23      }
24    }
25  });
26
27  await expect(addToIndexedDB(db, 'invalid', { id: 1 })).rejects.toThrow();
28  db.close();
29});

Common Use Cases

  • Adding New Items to Local Storage

    Save new records such as user preferences, offline tasks, or form submissions.

  • Client-Side Caching

    Persist API responses or static assets for offline or repeatable access.

  • Real-Time Queueing

    Store user actions or telemetry data locally before syncing with a remote server.

  • Local Backup Before Submit

    Temporarily store user-entered data in case of navigation, crashes, or submission failures.

  • Testing IndexedDB Store Behavior

    Insert test fixtures into stores to verify querying, indexing, or transaction handling.

Codebase: Utilities -> Storage -> addToIndexedDB | Yevhen Klymentiev