useIndexedDB

A React hook that abstracts the boilerplate of the IndexedDB API, facilitating database connections and transaction management.

Important

The onUpgrade callback is only triggered when the version number is incremented. This is the only place where you can safely create or modify object stores.

Caution

The store instance provided inside the withStore callback is only valid for the duration of that specific transaction. Do not store or use it outside the callback.

Note

Database connections are persistent once opened. Remember to call close() to release the database lock when the component is unmounted or the operation is finished.

Installation

bash

Description

The useIndexedDB hook simplifies working with the browser's low-level object-oriented database. It manages the connection lifecycle (opening and closing), handles schema upgrades via an onUpgrade callback, and provides a specialized withStore helper. This helper streamlines transaction creation and object store access, ensuring that operations are executed within the correct transactional context without manual state management of the database instance.

Parameters

NameTypeDescription
options.namestringThe name of the database to open.
options.versionnumberThe version of the database schema. Triggers onUpgrade if higher than current.
options.onUpgrade(db, old, new) => voidCallback to define or update the database schema (e.g., creating object stores).

Return values

NameTypeDescription
close() => voidCloses the active database connection and clears the internal reference.
deleteDatabase() => Promise<void>Closes the connection and deletes the database from the browser.
open() => Promise<IDBDatabase>Manually opens a connection to the database.
withStore(storeName, fn, options) => PromiseWraps a function in a transaction, providing direct access to a specific object store.

Demo

IndexedDB

Source code

tsx