This tutorial walks through building a full client-side database using IndexedDB and Dexie.js. We'll cover setup, data modeling, caching, and real-world usage.
First, let's create a simple database with a projects table:
const db = new Dexie('MyDB');
db.version(1).stores({
projects: '++id, title, created_at'
});
Create reusable models for data operations:
// Example from the Project model
static async create(data) {
return dbWrapper(async () => {
const id = await db.projects.add({
title: data.title,
description: data.description,
status: 'active'
});
return this.getById(id);
});
}
Implement caching for better performance:
// Example from Cache utility
static async get(key) {
const entry = await db.cache.get(key);
if (!entry) return null;
if (Date.now() - entry.timestamp > this.EXPIRE_TIME) {
await this.delete(key);
return null;
}
return entry.value;
}
Use with React components:
function useCachedData(key, fetcher) {
const [data, setData] = React.useState(null);
React.useEffect(() => {
async function getData() {
let cached = await Cache.get(key);
if (cached) {
setData(cached);
return;
}
const fresh = await fetcher();
await Cache.set(key, fresh);
setData(fresh);
}
getData();
}, [key]);
return data;
}