IndexedDB is a powerful client-side database that allows web applications to store and retrieve large amounts of structured data. When combined with Dexie.js, it becomes even more powerful and easier to use.
- Stores large amounts of data locally
- Works offline
- Highly performant
- Supports complex data structures
First, include Dexie.js in your project:
Create your first database with a simple table:
const db = new Dexie('MyDB');
db.version(1).stores({
projects: '++id, title, created_at' // ++ means auto-incrementing
});
Try adding some projects to see IndexedDB in action:
Create structured models to handle data operations:
// Project Model Example
const Project = {
async create(data) {
return db.projects.add({
title: data.title,
description: data.description,
status: 'active',
created_at: new Date()
});
},
async list(filters = {}) {
let collection = db.projects;
if (filters.status) {
collection = collection.filter(p => p.status === filters.status);
}
return collection.toArray();
}
};
Add caching to improve performance:
const Cache = {
EXPIRE_TIME: 5 * 60 * 1000, // 5 minutes
async get(key) {
const entry = await db.cache.get(key);
if (!entry || Date.now() - entry.timestamp > this.EXPIRE_TIME) {
return null;
}
return entry.value;
},
async set(key, value) {
await db.cache.put({
key,
value,
timestamp: Date.now()
});
}
};
Use IndexedDB 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;
}
Here's an advanced demo with search and filtering: