Lesson 15 / 29

IndexedDB & storage

Store large amounts of data locally using IndexedDB and Cache API.

Local storage options

IndexedDB stores structured data in objects/indexes. Cache API is optimized for responses. Choose IndexedDB for app data, Cache API for HTTP responses and static assets.

Store and retrieve from IndexedDB

Use IndexedDB to store app data like todos, notes, or user preferences.

const dbRequest = indexedDB.open('AppDB', 1);
dbRequest.onsuccess = () => {
  const db = dbRequest.result;
  const store = db.transaction('todos', 'readwrite').objectStore('todos');
  store.add({ id: 1, title: 'Learn PWA', completed: false });
};

dbRequest.onupgradeneeded = event => {
  const db = event.target.result;
  db.createObjectStore('todos', { keyPath: 'id' });
};

Output:

App data persisted in IndexedDB for offline access.

A common trap

IndexedDB transactions can be complex. Always handle onsuccess and onerror events, and remember that storage quotas vary by browser.

Database design for offline apps

Schema design patterns for efficient offline data management.