IndexedDB - Deleting Data
IndexedDB - Deleting Data
Section titled “IndexedDB - Deleting Data”Deleting data is a fundamental database operation. In IndexedDB, you can remove records from an object store using the .delete() method. This operation, like all data modifications, must be performed within a ‘readwrite’ transaction.
Syntax
Section titled “Syntax”const request = objectStore.delete(key);The .delete() method takes the primary key of the record you wish to remove. It returns an IDBRequest object. You can listen for the success event on this request to confirm the deletion.
Example: Deleting a Record by Key
Section titled “Example: Deleting a Record by Key”This example demonstrates a modern, structured approach to populating a database, deleting a specific item, and then verifying the result.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>IndexedDB Deleting Data</title></head><body> <h1>Check the console for output.</h1> <div id="output"></div>
<script> const DB_NAME = "TodoAppDB"; const DB_VERSION = 1; const STORE_NAME = "tasks"; const outputDiv = document.getElementById('output');
// Helper to open the database function openDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = event => { const db = event.target.result; if (!db.objectStoreNames.contains(STORE_NAME)) { db.createObjectStore(STORE_NAME, { keyPath: "id", autoIncrement: true }); } }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); }
// Helper to perform a transaction async function performTransaction(storeName, mode, action) { const db = await openDB(); return new Promise((resolve, reject) => { const transaction = db.transaction(storeName, mode); const store = transaction.objectStore(storeName); action(store, resolve, reject); transaction.onerror = () => reject(transaction.error); }); }
// Add initial data async function populateData() { console.log("Populating initial data..."); const tasks = [ { text: "Learn IndexedDB", completed: true }, { text: "Build a PWA", completed: false }, // This will get id: 2 { text: "Deploy the app", completed: false } ]; // The action for the transaction const addAction = (store, resolve) => { tasks.forEach(task => store.add(task)); resolve(); }; await performTransaction(STORE_NAME, 'readwrite', addAction); console.log("Data populated."); }
// Delete an item by its key async function deleteTask(key) { console.log(`Attempting to delete task with key: ${key}`); const deleteAction = (store, resolve) => { const request = store.delete(key); request.onsuccess = () => { console.log(`Task ${key} deleted successfully.`); resolve(); } }; await performTransaction(STORE_NAME, 'readwrite', deleteAction); }
// Get all remaining items to verify async function getAllTasks() { const getAction = (store, resolve) => { const request = store.getAll(); request.onsuccess = () => resolve(request.result); }; return await performTransaction(STORE_NAME, 'readonly', getAction); }
async function main() { try { await populateData(); let tasks = await getAllTasks(); console.log("Tasks before deletion:", tasks); outputDiv.innerHTML += `<p>Before: ${JSON.stringify(tasks)}</p>`;
// Let's delete the task with key 2 ('Build a PWA') await deleteTask(2);
tasks = await getAllTasks(); console.log("Tasks after deletion:", tasks); outputDiv.innerHTML += `<p>After deleting item with key 2: ${JSON.stringify(tasks)}</p>`;
} catch (error) { console.error("An error occurred in main execution:", error); } }
// Clear DB on start for a clean run indexedDB.deleteDatabase(DB_NAME).onsuccess = main;
</script></body></html>Best Practices
Section titled “Best Practices”- Encapsulate Logic: Create helper functions for database operations (e.g.,
openDB,deleteItem). This makes your main application logic cleaner and easier to read. - Verify Deletion: After a delete operation, it’s good practice to fetch the data again to ensure the state is what you expect, especially during development.
- Bulk Deletion: To delete multiple records, you can iterate with a cursor and call
cursor.delete()for each record that matches your criteria. For deleting all records, theobjectStore.clear()method is more efficient than deleting one by one.