getAllFromIndexedDB
Retrieves all records from an object store in IndexedDB.
1/**
2 * Retrieves all records from an object store in IndexedDB.
3 *
4 * @param db - The open IDBDatabase instance.
5 * @param storeName - The name of the object store.
6 * @returns A Promise that resolves with an array of all records in the store.
7 */
8export function getAllFromIndexedDB<T = any>(
9 db: IDBDatabase,
10 storeName: string
11): Promise<T[]> {
12 return new Promise((resolve, reject) => {
13 const transaction = db.transaction([storeName], 'readonly');
14 const store = transaction.objectStore(storeName);
15 const request = store.getAll();
16
17 request.onsuccess = () => resolve(request.result);
18 request.onerror = () => reject(request.error);
19 });
20}
Promise-Based Retrieval
Converts the asynchronous IndexedDB call into a Promise, making it compatible with
async/await
and easier to compose.Generic Type Flexibility
Supports generic typing with
<T>
, enabling predictable output types and reducing reliance on type casting.Read-Only Safety
Uses a
readonly
transaction to prevent accidental modifications and avoid potential concurrency issues.Batch Efficiency
Retrieves all records in a single request, which is typically more performant than iterating via a cursor for most use cases.
Tests | Examples
1import { openIndexedDB } from './openIndexedDB';
2import { addToIndexedDB } from './addToIndexedDB';
3
4test('getAllFromIndexedDB - retrieves all records from store', async () => {
5 const db = await openIndexedDB('TestDB_GetAll', 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: 1, name: 'Alpha' });
14 await addToIndexedDB(db, 'items', { id: 2, name: 'Beta' });
15
16 const records = await getAllFromIndexedDB(db, 'items');
17
18 expect(records).toEqual([
19 { id: 1, name: 'Alpha' },
20 { id: 2, name: 'Beta' }
21 ]);
22
23 db.close();
24});
25
26test('getAllFromIndexedDB - returns empty array if store is empty', async () => {
27 const db = await openIndexedDB('TestDB_GetAllEmpty', 1, {
28 upgrade(db) {
29 db.createObjectStore('emptyStore', { keyPath: 'id' });
30 }
31 });
32
33 const records = await getAllFromIndexedDB(db, 'emptyStore');
34 expect(records).toEqual([]);
35
36 db.close();
37});
Common Use Cases
Rendering Lists from Local DB
Load and display all items (e.g. tasks, bookmarks, cached posts) from an IndexedDB store.
Search or Filter Operations
Retrieve the full dataset client-side for filtering, sorting, or searching in memory.
Data Synchronization
Pull all local records for comparison or syncing with a remote server.
Backup or Export Features
Gather the entire contents of a store to export or save elsewhere.
Development and Debugging
Easily inspect all stored data while developing or troubleshooting.