React IndexedDB Hook

1.0.14 · maintenance · verified Wed Apr 22

The `react-indexed-db-hook` package provides a React hook-based abstraction over the browser's native IndexedDB API. It simplifies common database operations like initializing the database, creating object stores, and performing CRUD operations (add, get, update, delete) within React components. The current stable version is 1.0.14, last published over three years ago, indicating a slower release cadence, likely in maintenance mode rather than active development with new features. It aims to make the powerful, asynchronous, and transactional IndexedDB API more accessible to React developers, offering a more robust client-side storage solution than `localStorage` for larger, structured datasets, and enabling offline-first application capabilities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the IndexedDB database, adding a new user to an object store, and retrieving all users using the `useIndexedDB` hook. This covers basic setup and CRUD operations.

import React, { useEffect, useState } from 'react';
import { initDB, useIndexedDB } from 'react-indexed-db-hook';

interface User {
  id?: number;
  name: string;
  email: string;
}

// 1. Define your database configuration
const dbConfig = {
  name: 'MyDatabase',
  version: 1,
  objectStoresMeta: [
    {
      store: 'users',
      storeConfig: { keyPath: 'id', autoIncrement: true },
      storeSchema: [
        { name: 'name', keypath: 'name', options: { unique: false } },
        { name: 'email', keypath: 'email', options: { unique: true } },
      ],
    },
  ],
};

// 2. Initialize the database (typically once in your app's entry point)
initDB(dbConfig);

function UserForm() {
  const { add, getAll } = useIndexedDB<User>('users');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [users, setUsers] = useState<User[]>([]);

  useEffect(() => {
    // Fetch all users on component mount
    getAll().then((data) => {
      setUsers(data);
    });
  }, [getAll]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name || !email) return;

    try {
      const userId = await add({ name, email });
      alert(`User added with ID: ${userId}`);
      setName('');
      setEmail('');
      // Re-fetch users to update the list
      getAll().then((data) => setUsers(data));
    } catch (error) {
      console.error('Error adding user:', error);
      alert('Failed to add user. Email might already exist.');
    }
  };

  return (
    <div>
      <h1>Add New User</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <button type="submit">Add User</button>
      </form>

      <h2>Users List</h2>
      {users.length === 0 ? (
        <p>No users yet.</p>
      ) : (
        <ul>
          {users.map((user) => (
            <li key={user.id}>
              {user.name} ({user.email})
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default UserForm;

view raw JSON →