IndexedDB - Updating Data
IndexedDB - Creating and Updating Data
Section titled “IndexedDB - Creating and Updating Data”Once your database and object stores are set up, the next step is to populate them with data. IndexedDB provides two primary methods for writing data: put() and add(). All write operations must happen inside a readwrite transaction.
The Difference: put() vs. add()
Section titled “The Difference: put() vs. add()”Understanding the distinction between these two methods is crucial for preventing data loss or unexpected errors.
- objectStore.put(data, [key]): This method performs an “upsert” (update or insert). If an object with the same primary key already exists in the store, it will be completely replaced with the new
data. If no object with that key exists, a new one is created. This is the most commonly used method. - objectStore.add(data, [key]): This method is for insertion only. It adds the new
datato the store. If an object with the same primary key already exists, the operation will fail, and the request’serrorevent will fire with aConstraintError. Useadd()when you want to guarantee you are not overwriting existing data.
Example: A Practical Update Flow
Section titled “Example: A Practical Update Flow”This example shows a common pattern: adding initial data, retrieving a specific record, modifying it, and then using put() to save the changes back to the database. We will use the recommended idb library for a much cleaner and more readable async/await syntax.
<!DOCTYPE html><html lang="en"><head> <title>IndexedDB Updating Data Example</title> <script type="module" src="app.js"></script></head><body> <h1>Updating Data in IndexedDB</h1> <p>Check the console for output.</p></body></html>// app.jsimport { openDB } from 'https://cdn.jsdelivr.net/npm/idb@7/build/esm/index.js';
const DB_NAME = 'BotDatabaseV2';const STORE_NAME = 'bots';
async function dataUpdateDemo() { const db = await openDB(DB_NAME, 1, { upgrade(db) { if (!db.objectStoreNames.contains(STORE_NAME)) { db.createObjectStore(STORE_NAME, { keyPath: 'id' }); } }, });
// 1. Add some initial data using add() console.log('Adding initial bots...'); const txAdd = db.transaction(STORE_NAME, 'readwrite'); try { await Promise.all([ txAdd.store.add({ id: 1, name: 'Jason', branch: 'IT', version: 1 }), txAdd.store.add({ id: 2, name: 'Praneeth', branch: 'CSE', version: 1 }), txAdd.store.add({ id: 4, name: 'Abdul', branch: 'IT', version: 1 }), ]); await txAdd.done; console.log('Initial bots added.'); } catch (error) { if (error.name === 'ConstraintError') { console.warn('Initial data already exists. Skipping add.'); // Abort the transaction if there's a constraint error to be safe txAdd.abort(); } else { console.error('Error adding bots:', error); } }
// 2. Read, modify, and update a record using put() console.log('\n--- Updating Bot ID 4 ---'); const txUpdate = db.transaction(STORE_NAME, 'readwrite');
// Get the bot to update const botToUpdate = await txUpdate.store.get(4); console.log('Original bot data:', botToUpdate);
if (botToUpdate) { // Modify its properties botToUpdate.name = 'Abdul Rahman'; botToUpdate.version = 2;
// Use put() to save the changes await txUpdate.store.put(botToUpdate); console.log('Bot updated with put().'); } await txUpdate.done;
// 3. Verify the update console.log('\n--- Verifying Update ---'); const updatedBot = await db.get(STORE_NAME, 4); console.log('Fetched bot data after update:', updatedBot);
db.close();}
dataUpdateDemo();Common Pitfalls
Section titled “Common Pitfalls”- Forgetting to use
put(): Modifying a JavaScript object you retrieved from the database does NOT automatically save it. You must explicitly callput()within areadwritetransaction to persist the changes. add()on existing data: Callingadd()with a key that is already in the object store will throw aConstraintErrorand abort the entire transaction. Any other operations within that transaction will be rolled back.