CodeBlanks Logo Icon CodeBlanks

Summary - IndexedDB

JavaScript course · Advanced · Lesson 89/100

Build an app that persistently stores notes data using IndexedDB.

Summary - IndexedDB flow

An IndexedDB flow has four steps: open, build the structure, do the work, receive the result. First you open the database with indexedDB.open; inside onupgradeneeded you create stores and indexes.

Then you start a transaction with db.transaction, call add, get or getAll through objectStore, and read the result with request.onsuccess.

Exercise Open NotesDB, create the store and add a note

Open the 'NotesDB' database at version 1 with indexedDB.open and assign it to request. In request.onupgradeneeded, read event.target.result into db and create the 'notes' store with { keyPath: 'id' }. In request.onsuccess, read event.target.result into db, open a 'readwrite' transaction, get objectStore('notes') and call add with { id: 1, text: 'First note' }.

Show example solution
const request = indexedDB.open('NotesDB', 1);
request.onupgradeneeded = function(event) {
  const db = event.target.result;
  db.createObjectStore('notes', { keyPath: 'id' });
};
request.onsuccess = function(event) {
  const db = event.target.result;
  const tx = db.transaction('notes', 'readwrite');
  const store = tx.objectStore('notes');
  store.add({ id: 1, text: 'First note' });
};

Summary - key points

The essentials of IndexedDB: an asynchronous API, transaction-based access, object stores for record collections, keyPath for the key field, and indexes for fast lookups. Structure changes happen only inside onupgradeneeded.

Data is persistent in the browser; even large objects and files can be stored. Use console.log to print intermediate values and trace the flow.

Exercise Fetch all notes

Open a 'readonly' transaction on the 'notes' store with db.transaction and assign it to tx. Assign tx.objectStore('notes').getAll() to a request variable. Inside request.onsuccess, log request.result with console.log.

Show example solution
const tx = db.transaction('notes', 'readonly');
const request = tx.objectStore('notes').getAll();
request.onsuccess = function(event) {
  console.log(request.result);
};

Test yourself

  1. Which method overwrites an existing record?

    • store.put
    • store.add
    • store.set
    • store.update
    Show answer

    store.put — Correct! store.put overwrites an existing record, or inserts if missing.

  2. Match the IndexedDB pipeline

    indexedDB.open
    open the database
    onupgradeneeded
    build the structure
    db.transaction
    start a transaction
    store.add
    add a record
    request.onsuccess
    receive the result

All lessons in Advanced