shadcn-ahooks
External Hooks

useIndexedDB

The API useIndexedDB

useIndexedDB

A hook for managing IndexedDB storage with a simple and intuitive API.

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useIndexedDB.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useIndexedDB.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useIndexedDB.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useIndexedDB.json

Examples

Default usage

import React from "react";
import useIndexedDB, { setupIndexedDB } from '@/src/hooks/external-hooks/useIndexedDB';

// Database Configuration
const idbConfig = {
  databaseName: "fruity-db",
  version: 1,
  stores: [
    {
      name: "fruits",
      id: { keyPath: "id", autoIncrement: true },
      indices: [
        { name: "name", keyPath: "name", options: { unique: false } },
        { name: "quantity", keyPath: "quantity" },
      ],
    },
  ],
};

const Example = () => {
  useEffect(() => {
    setupIndexedDB(idbConfig)
      .then(() => console.log("success"))
      .catch(e => console.error("error / unsupported", e));
  }, []);

  const { add } = useIndexedDBStore("fruits");

  const insertFruit = () => {
    add({ name: "Mango 🥭", quantity: 2 }).then(console.log);
  };

  return <button onClick={insertFruit}>Insert</button>;
};

export default Example;

API

setupIndexedDB

Before using the useIndexedDB hook, you need to initialize the database configuration using setupIndexedDB.

interface IndexedDBColumn {
  name: string;
  keyPath: string;
  options?: IDBIndexParameters;
}

interface IndexedDBStore {
  name: string;
  id: IDBObjectStoreParameters;
  indices: IndexedDBColumn[];
}

interface IndexedDBConfig {
  databaseName: string;
  version: number;
  stores: IndexedDBStore[];
}

setupIndexedDB(config: IndexedDBConfig): Promise<void>

Config

PropertyDescriptionTypeDefault
databaseNameThe name of the IndexedDB databasestring-
versionThe version of the database schemanumber-
storesArray of object store configurationsIndexedDBStore[]-

IndexedDBStore

PropertyDescriptionTypeDefault
nameThe name of the object storestring-
idObject store parameters (e.g., keyPath, autoIncrement)IDBObjectStoreParameters-
indicesArray of index configurationsIndexedDBColumn[]-

IndexedDBColumn

PropertyDescriptionTypeDefault
nameThe name of the indexstring-
keyPathThe key path for the indexstring-
optionsOptional index parametersIDBIndexParameters-

useIndexedDB

const {
  getByID,
  getOneByKey,
  getManyByKey,
  getAll,
  add,
  update,
  deleteByID,
  deleteAll,
  openCursor,
} = useIndexedDB<T>(storeName: string);

Params

PropertyDescriptionTypeDefault
storeNameThe name of the object store to operate onstring-

Result

PropertyDescriptionType
getByIDGet a record by its primary key(id: string | number) => Promise<T>
getOneByKeyGet a single record by an indexed key(keyPath: string, value: string | number) => Promise<T | undefined>
getManyByKeyGet multiple records by an indexed key(keyPath: string, value: string | number) => Promise<T[]>
getAllGet all records from the store() => Promise<T[]>
addAdd a new record to the store(value: T, key?: any) => Promise<number>
updateUpdate an existing record (or insert if not exists)(value: T, key?: any) => Promise<any>
deleteByIDDelete a record by its primary key(id: any) => Promise<any>
deleteAllClear all records from the store() => Promise<any>
openCursorOpen a cursor to iterate over records(cursorCallback: (e: Event) => any, keyRange?: IDBKeyRange) => Promise<IDBCursorWithValue | void>

Usage Example

import useIndexedDB, { setupIndexedDB } from '@/src/hooks/external-hooks/useIndexedDB';

// Initialize the database (typically in your app's entry point)
await setupIndexedDB({
  databaseName: 'MyDatabase',
  version: 1,
  stores: [
    {
      name: 'users',
      id: { keyPath: 'id', autoIncrement: true },
      indices: [
        { name: 'name', keyPath: 'name', options: { unique: false } },
        { name: 'email', keyPath: 'email', options: { unique: true } },
      ],
    },
  ],
});

// In your component
function UserComponent() {
  const { add, getAll, getByID, update, deleteByID } = useIndexedDB<User>('users');

  const addUser = async () => {
    const id = await add({ name: 'John Doe', email: 'john@example.com' });
    console.log('Added user with id:', id);
  };

  const fetchUsers = async () => {
    const users = await getAll();
    console.log('All users:', users);
  };

  return (
    // ...
  );
}

Notes

  • Make sure to call setupIndexedDB before using useIndexedDB in any component.
  • The hook uses the browser's native IndexedDB API, so it's only available in browser environments.
  • All operations return Promises, so you should handle them with async/await or .then().

On this page