Challenge - IndexedDB app
Build a bookmarks app's add-and-query flow with IndexedDB.
IndexedDB app
In this challenge you will write the data flow for a bookmarks app. First you open the database with indexedDB.open('bookmarks', 1); the second argument is the version number.
On first open the onupgradeneeded event fires. Here you create the store with db.createObjectStore('marks', { keyPath: 'id' }). Think of it like a table.
To add data you open a transaction, get objectStore('marks') and call add(bookmark). All operations must happen inside a transaction.
Adding and querying data
A transaction is an atomic operation on one or more object stores. With db.transaction('marks', 'readwrite') you get read and write permission.
You get objectStore('marks') from it, then add a new record with store.add(bookmark). Each operation returns a request; onsuccess tells you it worked.
To query you open the same flow with 'readonly', then call store.get(id) or search through an index with store.index('title').
Exercise Write the addBookmark function
Write addBookmark(db, bookmark): open a readwrite transaction with db.transaction('marks', 'readwrite'), get objectStore('marks') and add the bookmark with store.add(bookmark).
Show example solution
Open function addBookmark(db, bookmark). Inside, write const tx = db.transaction('marks', 'readwrite'); const store = tx.objectStore('marks'); store.add(bookmark);.
Example solution:
function addBookmark(db, bookmark) {
const tx = db.transaction('marks', 'readwrite');
const store = tx.objectStore('marks');
store.add(bookmark);
}
Test yourself
-
Open the database
const request = ____; request.onupgradeneeded = (event) => { const db = event.target.result; db.createObjectStore('marks', { keyPath: 'id' }); };Show answer
const request = indexedDB.open('bookmarks', 1); request.onupgradeneeded = (event) => { const db = event.target.result; db.createObjectStore('marks', { keyPath: 'id' }); }; -
How do you get the objectStore to add data?
const tx = db.transaction('marks', 'readwrite'); const store = tx.objectStore('marks'); store.add(bookmark);- Directly on the db object
- The indexedDB global
- event.target.result
- Through a transaction
Show answer
Through a transaction — Correct! All data operations go through an objectStore inside a transaction.
-
Match the IndexedDB concepts
- indexedDB.open
- Opens the database
- onupgradeneeded
- Creates the store
- transaction()
- Starts an atomic op
- objectStore()
- Reaches the store