Course contentsShow
← Web Development
Lesson 791 of 2,98214. Browser StorageFree lesson

Updating and Deleting Records

Modify existing data with put() and remove records using delete() within transactions.

Updating and Deleting Records

What you'll learn: How to modify existing IndexedDB records with put() and remove them with delete() within transactions.

Changing Data After It's Stored

Once you've added data to IndexedDB, you'll often need to update or remove records. Both operations require write transactions and use the object store methods you've already learned about.

Updating records uses the same put() method you used for adding data. If you provide a key that already exists, IndexedDB replaces the old record with the new one. Think of it like editing a contact in your phone—you're overwriting what was there before.

Deleting records uses the delete() method, which removes a record by its key. It's like erasing an entry from a notebook—once it's gone, it's gone (unless you add it again).

How It Works

const transaction = db.transaction(['users'], 'readwrite');
const store = transaction.objectStore('users');

// Update: overwrites existing record with key 1
const updatedUser = { id: 1, name: 'Jane Doe', age: 31 };
const updateRequest = store.put(updatedUser);

updateRequest.onsuccess = () => {
  console.log('User updated successfully');
};

// Delete: removes the record with key 2
const deleteRequest = store.delete(2);

deleteRequest.onsuccess = () => {
  console.log('User deleted successfully');
};

transaction.oncomplete = () => {
  console.log('Transaction finished');
};

Both operations are asynchronous and emit success/error events. The transaction commits automatically when all requests complete successfully.

Key Takeaway: Use put() to update existing IndexedDB records (same method as adding, but with an existing key) and delete() to remove records by their key—both within readwrite transactions.