Adding and reading data
Learn to add and get data through a transaction.
What is a transaction?
Every read and write in IndexedDB happens inside a transaction. You start one with db.transaction(storeName, mode). The mode is either 'readonly' or 'readwrite'.
const tx = db.transaction('notes', 'readwrite');A transaction gives the store a consistent scope; on error, all changes are rolled back. When the work is done, the transaction closes automatically.
Adding and reading data
From the transaction, you get the store with objectStore('notes'), then add a new record with store.add(obj). To read a record, use store.get(key).
const store = tx.objectStore('notes');
store.add({ id: 1, text: 'Hello' });Both calls return an IDBRequest; you read the result with request.onsuccess. Calling add with an existing key throws; use put to overwrite.
Exercise Add a note through a transaction
Open a 'readwrite' transaction on the 'notes' store with db.transaction and assign it to tx. Get the store with tx.objectStore('notes') into a store variable. Call store.add with the object { id: 1, text: 'Hello' }.
Show example solution
const tx = db.transaction('notes', 'readwrite');
const store = tx.objectStore('notes');
store.add({ id: 1, text: 'Hello' });
Test yourself
-
Match transaction parts
- 'readonly'
- read only
- 'readwrite'
- read and write
- objectStore()
- get the store
- transaction()
- start operation
-
Add a new record to the store
store.____({ id: 1, text: 'Hello' });Show answer
store.add({ id: 1, text: 'Hello' }); -
Which mode is used to add data?
- 'readonly'
- 'readwrite'
- 'writeonly'
- 'add'
Show answer
'readwrite' — Correct! Inside a 'readwrite' transaction you can call add and put.