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

clearIndexedDBStore

Clears all records from a specified object store in IndexedDB.

TypeScript
Copied!
1/**
2 * Clears all records from a specified object store in IndexedDB.
3 *
4 * @param db - The open IDBDatabase instance.
5 * @param storeName - The name of the object store to clear.
6 * @returns A Promise that resolves when the store is cleared.
7 */
8export function clearIndexedDBStore(
9  db: IDBDatabase,
10  storeName: string
11): Promise<void> {
12  return new Promise((resolve, reject) => {
13    const transaction = db.transaction([storeName], 'readwrite');
14    const store = transaction.objectStore(storeName);
15    const request = store.clear();
16
17    request.onsuccess = () => resolve();
18    request.onerror = () => reject(request.error);
19  });
20}
  • Efficient Store Reset

    Uses the native .clear() method, which is optimized for bulk deletion over looping or individual deletions.

  • Simple and Focused API

    Provides a concise and readable way to wipe a store without boilerplate.

  • Transaction-Based Execution

    Runs in a readwrite transaction, ensuring consistency and rollback capabilities in case of failure.

  • Promise-Based Design

    Seamlessly integrates into modern async/await workflows with clear success and failure handling.

Tests | Examples

TypeScript
Copied!
1import { openIndexedDB } from './openIndexedDB';
2import { addToIndexedDB } from './addToIndexedDB';
3import { getAllFromIndexedDB } from './getAllFromIndexedDB';
4
5test('clearIndexedDBStore - removes all items from the store', async () => {
6  const db = await openIndexedDB('TestDB_Clear', 1, {
7    upgrade(db) {
8      db.createObjectStore('entries', { keyPath: 'id' });
9    }
10  });
11
12  await addToIndexedDB(db, 'entries', { id: 1, name: 'One' });
13  await addToIndexedDB(db, 'entries', { id: 2, name: 'Two' });
14
15  await clearIndexedDBStore(db, 'entries');
16
17  const all = await getAllFromIndexedDB(db, 'entries');
18  expect(all).toEqual([]);
19
20  db.close();
21});

Common Use Cases

  • Cache Invalidation

    Clear outdated cached data (e.g., on logout or version change).

  • Factory Reset Scenarios

    Reset app state to defaults by purging IndexedDB stores.

  • Development and Testing

    Clean object stores between test runs or debugging sessions.

  • User-Triggered Data Wipe

    Allow users to manually clear stored data, e.g., via settings or a “Clear All” button.

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