indexeddb

Framework: react

πŸ“¦ Installation

Install the latest version using npm:

bash
npm install universe-code@latest

1️⃣ Create IndexedDB Provider

Create the following file:

πŸ“ lib/provider/idb-provider.tsx

ts
"use client";

import { configureIdb } from "universe-code/react";

export function IdbProvider() {
  configureIdb({
    dbName: "db",
    dbVersion: 1,
    storeName: "store",
  });

  return null;
}

2️⃣ Register Provider in Root Layout

Call the provider once so IndexedDB initializes globally.

ts
import { IdbProvider } from "@/lib/provider/idb-provider";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <IdbProvider />
        {children}
      </body>
    </html>
  );
}

βœ… IndexedDB is now created and ready to use.

πŸš€ Using IndexedDB in Components Import the Hook

ts
import { useIdbStore } from "universe-code/react";

Initialize Store

ts
const idbStore = useIdbStore();

All IndexedDB helper functions are now available inside idbStore.


πŸ” Store api data in indexdb with time interval.

Fetch API data and automatically store it in IndexedDB with expiry control.

ts
idbStore
  .getWithExpiry("users", minutesToMs(1), async () => {
    const res = await fetch("https://example.com/api/user", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    const data = await res.json();
    return data.data;
  })
  .then(console.log);

Note:

import minutesToMs() from universe-code/core

ts
import { minutesToMs } from "universe-code/core";

🧠 How it works

  • Calls API only if data is missing or expired
  • Saves response in IndexedDB
  • Returns cached data instantly on next call

πŸ“₯ Get Data from IndexedDB

ts
const data = await idbStore.get("users");
console.log(data);

✏️ Insert / Update Data

ts
idbStore.put({
  id: "users",
  data: {
    name: "Mark",
    country: "USA",
  },
});

πŸ—‘οΈ Delete a Specific Record

ts
idbStore.remove("users");

🧹 Clear Entire IndexedDB Store

ts
idbStore.clear();

πŸ“š API Reference

FunctionDescription
get(id)Retrieve data from IndexedDB
put(payload)Insert or update data
remove(id)Delete a record
clear()Clear all IndexedDB data
getWithExpiry(id, expiry, callback)Fetch and cache data with expiry

βœ… Ideal Use Cases

  • API response caching
  • Offline-first applications
  • Performance optimization
  • Reducing repeated API calls
  • Storing session or user data

πŸ›‘ License

MIT License Β© universe-code