IndexedDB
Write and read structured notes
Store real JavaScript values with put(), retrieve them by key, and distinguish insert-only behavior from replacement.
8 minute lesson
IndexedDB uses the structured clone algorithm. We can store a note with a Date without converting the whole record to JSON.
Use add() when an existing key should be an error. Use put() when the operation may insert or replace. Read one record with get(), and handle undefined when it does not exist.
const note = {
id: crypto.randomUUID(),
title: 'Trail conditions',
body: 'The north path is wet',
updatedAt: new Date(),
}
await db.put('notes', note)
const saved = await db.get('notes', note.id)
Functions and DOM elements cannot be cloned into the database. Store data, not live interface objects or behavior.
Do not call getAll() forever as the collection grows. A useful app needs indexes, bounds, and pagination or cursors.
Keep record IDs stable across edits. Replacing an ID creates a second note instead of updating the original record.
Add three notes, replace one with put(), then try the same key with add(). Record the returned record and the constraint failure.
Lesson completed