IndexedDB

Open a notes database

Create the field-notes IndexedDB database and its first object store with a small promise wrapper.

8 minute lesson

~~~

Saved notes are structured records that can grow. IndexedDB is the right browser database for this job.

The native API is event-based. We will use the small idb wrapper to work with promises while keeping IndexedDB concepts visible. Install it, open version 1, and create the store during the upgrade transaction.

import { openDB } from 'idb'

export const db = await openDB('field-notes', 1, {
  upgrade(db) {
    db.createObjectStore('notes', { keyPath: 'id' })
  },
})

An object store is a collection of records. The id property is our primary key. Schema changes such as creating stores and indexes belong in a version upgrade, not ordinary page code.

Open the database only in browser code. Server rendering environments do not provide IndexedDB.

Install idb, open version 1, and inspect the database in DevTools. Reload twice and prove the upgrade callback does not recreate the existing store.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →