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
| Function | Description |
|---|---|
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