IndexedDB with Dexie.js Tutorial

1. Getting Started

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.

Installation


      
    

2. Basic Database Setup

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'
      }); 
    

Try it:

3. Advanced Features

Data Models

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);
        });
      }
    

Caching

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;
      }
    

4. React Integration

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;
      }
    

5. Full Example