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

getFromIndexedDB

Retrieves a record from an object store in IndexedDB by key.

TypeScript
Copied!
1/**
2 * Retrieves a record from an object store in IndexedDB by key.
3 *
4 * @param db - The open IDBDatabase instance.
5 * @param storeName - The name of the object store.
6 * @param key - The key of the record to retrieve.
7 * @returns A Promise that resolves with the record or undefined if not found.
8 */
9export function getFromIndexedDB<T = any>(
10  db: IDBDatabase,
11  storeName: string,
12  key: IDBValidKey
13): Promise<T | undefined> {
14  return new Promise((resolve, reject) => {
15    const transaction = db.transaction([storeName], 'readonly');
16    const store = transaction.objectStore(storeName);
17    const request = store.get(key);
18
19    request.onsuccess = () => resolve(request.result);
20    request.onerror = () => reject(request.error);
21  });
22}
  • Generic Return Type

    Allows strong typing of the returned data through a generic <T>, reducing the need for type assertions elsewhere in the code.

  • Promise-Based Interface

    Converts the callback-based IndexedDB API into a Promise, improving readability and enabling async/await usage.

  • Read-Only Transaction Isolation

    Uses a readonly transaction for safe, non-intrusive access to data, reducing potential locking or write conflicts.

  • Graceful Fallback Handling

    Resolves to undefined if the record doesn’t exist, avoiding exceptions and simplifying null checks in calling code.

Tests | Examples

TypeScript
Copied!
1import { openIndexedDB } from './openIndexedDB';
2import { addToIndexedDB } from './addToIndexedDB';
3
4test('getFromIndexedDB - retrieves a record by key', async () => {
5  const db = await openIndexedDB('TestDB_Get', 1, {
6    upgrade(db) {
7      if (!db.objectStoreNames.contains('items')) {
8        db.createObjectStore('items', { keyPath: 'id' });
9      }
10    }
11  });
12
13  await addToIndexedDB(db, 'items', { id: 42, name: 'Answer' });
14
15  const item = await getFromIndexedDB(db, 'items', 42);
16
17  expect(item).toEqual({ id: 42, name: 'Answer' });
18  db.close();
19});
20
21test('getFromIndexedDB - returns undefined for missing key', async () => {
22  const db = await openIndexedDB('TestDB_GetMissing', 1, {
23    upgrade(db) {
24      db.createObjectStore('items', { keyPath: 'id' });
25    }
26  });
27
28  const result = await getFromIndexedDB(db, 'items', 999);
29  expect(result).toBeUndefined();
30
31  db.close();
32});

Common Use Cases

  • Loading Cached Records

    Retrieve previously saved data such as offline content, user preferences, or API responses.

  • Lazy Data Hydration

    Fetch related records on-demand without preloading the entire store.

  • Key-Based Lookup

    Perform quick access to data when you already know the primary key.

  • Pre-Fill Forms or UI State

    Populate UI components with stored values retrieved from IndexedDB.

  • Debugging or Admin Interfaces

    Retrieve records for inspection or display in dev tools or in-app dashboards.

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