To add data to an object store in IndexedDB, you typically perform this operation within a transaction. Here's a step-by-step guide on how to add data to an object store:
// Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);
// Step 2: Handle the database events
request.onerror = function(event) {
// Handle errors
console.log("Error opening database");
};
request.onsuccess = function(event) {
// Get reference to the opened database
var db = event.target.result;
console.log("Database opened successfully");
// Step 3: Start a transaction
var transaction = db.transaction(["myObjectStore"], "readwrite");
// Step 4: Get the object store
var objectStore = transaction.objectStore("myObjectStore");
// Step 5: Add data to the object store
var data = { id: 1, name: "John Doe", email: "john@example.com" };
var addRequest = objectStore.add(data);
// Step 6: Handle the result of the add operation
addRequest.onsuccess = function(event) {
console.log("Data added successfully");
};
addRequest.onerror = function(event) {
console.log("Error adding data");
};
};
// Step 7: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
// Get reference to the opened database
var db = event.target.result;
// Create an object store if it doesn't exist
var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });
// Define indexes if needed
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};?
Explanation :* Open or create a database using indexedDB.open("
myDatabase
", 1).
* Handle database events such as error and success.
* Start a transaction with the object store you want to add data to. In this case, we use "
myObjectStore
".
* Get a reference to the object store within the transaction using transaction.objectStore("
myObjectStore
").
* Prepare the data you want to add to the object store. This can be in the form of a JavaScript object.
* Use the
add()
method on the object store to add the data. The
add()
method takes the data as a parameter.
* Handle the result of the add operation using onsuccess and onerror event handlers.
* Optionally, define the database structure within the onupgradeneeded event handler.