Adding Data to Object Stores
You'll learn how to insert records into IndexedDB object stores using the add() method with proper error handling.
Now that you know how to create transactions and access object stores, it's time to actually put data into your database. Think of this like filling out a form and submitting it to a filing cabinet—you need to open the right drawer (transaction), find the right folder (object store), and carefully place your document inside.
Using transaction.objectStore().add()
To add data, you create a read-write transaction, access the object store, and call the add() method with your data object:
// Open a database connection
const request = indexedDB.open('MyDatabase', 1);
request.onsuccess = function(event) {
const db = event.target.result;
// Create a read-write transaction
const transaction = db.transaction(['users'], 'readwrite');
// Access the object store
const objectStore = transaction.objectStore('users');
// Add a record
const addRequest = objectStore.add({
id: 1,
name: 'Alice',
email: 'alice@example.com'
});
// Handle success
addRequest.onsuccess = function() {
console.log('Record added successfully');
};
// Handle errors
addRequest.onerror = function(event) {
console.error('Error adding record:', event.target.error);
};
};
Notice that add() returns its own request object. You should always attach both onsuccess and onerror handlers to catch issues like duplicate keys or constraint violations.
Key Takeaway: Use transaction.objectStore().add() to insert records into IndexedDB, and always include error handlers to catch issues like duplicate keys or transaction failures.