Registry / database / react-indexed-db

react-indexed-db

JSON →
library2.0.1jsnpmunverified

react-indexed-db-hook provides a simplified interface for interacting with the browser's IndexedDB, exposed as a React Hook. It is a fork of `react-indexed-db` that primarily focuses on a hook-based API for modern React applications. The current stable version is 2.0.1. While it offers a context-based API, the maintainer explicitly states a lack of future support for it, pushing users towards the `useIndexedDB` hook. The library aims to abstract away the complexities of IndexedDB, providing common CRUD operations (getByID, getAll, add, update, delete) through a concise hook interface, making client-side data persistence more accessible in React projects. Its release cadence appears to be feature-driven rather than time-boxed, with updates addressing bugs or adding minor enhancements. Key differentiators include its explicit focus on a modern React hook API and a lightweight abstraction over raw IndexedDB.

npm install react-indexed-db
INSTALL
IMPORT
SIG · REACT-INDEXED-DB
R
react-indexed-db
databasejavascriptv2.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

initDB
import { initDB } from 'react-indexed-db-hook';
const { initDB } = require('react-indexed-db-hook');
Required to initialize the IndexedDB configuration globally before any hooks or context are used. Typically called once at the application's entry point.
useIndexedDB
import { useIndexedDB } from 'react-indexed-db-hook';
import useIndexedDB from 'react-indexed-db-hook';
The primary hook for interacting with a specific object store. It's a named export, not a default export. Pass the store name as an argument.
IndexedDB (Context Provider)
import { IndexedDB } from 'react-indexed-db-hook';
import IndexedDB from 'react-indexed-db-hook';
Although available, the maintainer does not plan on supporting the context API in the future. Prefer `initDB` and `useIndexedDB`.
AccessDB (Context Consumer)
import { AccessDB } from 'react-indexed-db-hook';
Consumer for the `IndexedDB` context. Similar to `IndexedDB` provider, its use is discouraged due to lack of future support.

This quickstart demonstrates how to initialize the IndexedDB, use the `useIndexedDB` hook to perform CRUD operations (add, get, update, delete) on an 'items' object store, and display the items in a React component.

import React, { useEffect, useState } from 'react'; import { initDB, useIndexedDB } from 'react-indexed-db-hook'; // 1. Define your DB configuration export const DBConfig = { name: 'MyTestDB', version: 1, objectStoresMeta: [ { store: 'items', storeConfig: { keyPath: 'id', autoIncrement: true }, storeSchema: [ { name: 'name', keypath: 'name', options: { unique: false } }, { name: 'value', keypath: 'value', options: { unique: false } } ] } ] }; // 2. Initialize the DB once at the application entry point initDB(DBConfig); interface Item { id?: number; name: string; value: string; } const ItemManager: React.FC = () => { const { add, getAll, getByID, update, deleteRecord } = useIndexedDB<Item>('items'); const [items, setItems] = useState<Item[]>([]); const [newItemName, setNewItemName] = useState(''); const [newItemValue, setNewItemValue] = useState(''); const [selectedItemId, setSelectedItemId] = useState<number | null>(null); const [editItemName, setEditItemName] = useState(''); const [editItemValue, setEditItemNameValue] = useState(''); const refreshItems = async () => { const allItems = await getAll(); setItems(allItems); }; useEffect(() => { refreshItems(); }, []); const handleAddItem = async () => { await add({ name: newItemName, value: newItemValue }); setNewItemName(''); setNewItemValue(''); refreshItems(); }; const handleEditSelect = async (id: number) => { const item = await getByID(id); if (item) { setSelectedItemId(id); setEditItemName(item.name); setEditItemNameValue(item.value); } }; const handleUpdateItem = async () => { if (selectedItemId) { await update({ id: selectedItemId, name: editItemName, value: editItemValue }); setSelectedItemId(null); setEditItemName(''); setEditItemNameValue(''); refreshItems(); } }; const handleDeleteItem = async (id: number) => { await deleteRecord(id); refreshItems(); }; return ( <div> <h1>Items</h1> <div> <input type="text" placeholder="Name" value={newItemName} onChange={(e) => setNewItemName(e.target.value)} /> <input type="text" placeholder="Value" value={newItemValue} onChange={(e) => setNewItemValue(e.target.value)} /> <button onClick={handleAddItem}>Add Item</button> </div> {selectedItemId && ( <div> <h3>Edit Item (ID: {selectedItemId})</h3> <input type="text" value={editItemName} onChange={(e) => setEditItemName(e.target.value)} /> <input type="text" value={editItemValue} onChange={(e) => setEditItemNameValue(e.target.value)} /> <button onClick={handleUpdateItem}>Update Item</button> <button onClick={() => setSelectedItemId(null)}>Cancel</button> </div> )} <ul> {items.map((item) => ( <li key={item.id}> {item.name}: {item.value} <button onClick={() => handleEditSelect(item.id!)}>Edit</button> <button onClick={() => handleDeleteItem(item.id!)}>Delete</button> </li> ))} </ul> </div> ); }; export default ItemManager;
Debug
Known issues
deprecatedThe Context API (`<IndexedDB>` provider and `<AccessDB>` consumer) is not planned for future support by the maintainer. While it currently works, reliance on it may lead to issues with future updates or lack of bug fixes specific to the context API.
fix
Migrate existing code to use the `initDB` function for initialization and the `useIndexedDB` hook for all database interactions. This aligns with the library's primary focus.
affects: >=2.0.0
gotchaIt is crucial to call `initDB(DBConfig)` only once at the root level of your application, before any components that use `useIndexedDB` or `IndexedDB` context are mounted. Calling it multiple times or within a component's render cycle can lead to unexpected behavior or database initialization errors.
fix
Place `initDB(DBConfig)` in your main application file (e.g., `App.tsx` or `index.tsx`) outside of any React component or in a top-level effect that runs once.
affects: >=1.0.0
gotchaWhen defining `objectStoresMeta`, ensure that `keyPath` is correctly specified if you are relying on `getByID`, `update`, or `deleteRecord`. If `autoIncrement` is true, the database will handle key generation; otherwise, you must provide the key when adding records.
fix
Verify your `DBConfig.objectStoresMeta` definitions. For `getByID`, `update`, `deleteRecord`, your data objects must consistently have the property defined by `keyPath` (e.g., `id`). When `autoIncrement` is false, make sure to explicitly provide the key in `add` operations.
affects: >=1.0.0
Errors
Common errors & fixes
Uncaught (in promise) DOMException: The database is not running any transactions.
This usually indicates that `initDB` was not called or failed before attempting to use database operations via `useIndexedDB`.
fix
Ensure `initDB(DBConfig)` is called successfully at your application's entry point, before any components requiring IndexedDB access are rendered.
Property 'add' does not exist on type '{ ... }'. Did you mean 'addRecord'?
Incorrect method name or type inference issue. The library provides `add`, `getAll`, `getByID`, `update`, `deleteRecord`.
fix
Double-check the method names from the `useIndexedDB` hook. The correct method for adding a record is `add` (not `addRecord` or `insert`). Ensure your TypeScript generic `useIndexedDB<T>` correctly reflects the type of objects in your store.
Uncaught (in promise) DOMException: An object store with the specified name was not found or has been deleted.
The object store name provided to `useIndexedDB('storeName')` does not match any store defined in `DBConfig.objectStoresMeta`.
fix
Verify that the string argument passed to `useIndexedDB` exactly matches the `store` property in one of your `objectStoresMeta` configurations in `DBConfig`.
Upgrade
Version history
2.0.1latest on npm
Audit
Dependencies
reactrequiredPeer dependency required for all React components and hooks.
Agent activity
9 hits · last 30 days
node
8
Meta
1
Resources
react-indexed-db — npm install react-indexed-db · libregistry