IndexedDB with Dexie.js Tutorial

1. Introduction to IndexedDB

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.

Why Use IndexedDB?

- Stores large amounts of data locally
- Works offline
- Highly performant
- Supports complex data structures

2. Getting Started

First, include Dexie.js in your project:


      
    

Basic Database Setup

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

Live Demo: Basic Project Manager

Try adding some projects to see IndexedDB in action:

3. Advanced Database Operations

Data Models

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

4. Implementing Caching

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

5. React Integration

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

6. Full Example

Here's an advanced demo with search and filtering: