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
Name
Type
Description
options.name
string
The name of the database to open.
options.version
number
The version of the database schema. Triggers onUpgrade if higher than current.
options.onUpgrade
(db, old, new) => void
Callback to define or update the database schema (e.g., creating object stores).
Return values
Name
Type
Description
close
() => void
Closes 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) => Promise
Wraps a function in a transaction, providing direct access to a specific object store.