It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 60 - Adding and Updating Data in IndexedDB

IndexedDB allows us to store and manage large amounts of structured data in the browser. In this lesson, we will cover how to add and update data in an IndexedDB database.

1. Opening a Database and Creating an Object Store

Before adding or updating data, we must open a database and create an object store.

let db;

const request = indexedDB.open("MyDatabase", 1);

request.onupgradeneeded = function(event) {
    db = event.target.result;
    if (!db.objectStoreNames.contains("users")) {
        db.createObjectStore("users", { keyPath: "id" });
    }
};

request.onsuccess = function(event) {
    db = event.target.result;
    console.log("Database opened successfully");
};

request.onerror = function(event) {
    console.log("Error opening database:", event.target.errorCode);
};

2. Adding Data to IndexedDB

We can add new data using a transaction and the add() method:

function addUser(id, name, age) {
    let transaction = db.transaction(["users"], "readwrite");
    let store = transaction.objectStore("users");

    let user = { id: id, name: name, age: age };

    let request = store.add(user);

    request.onsuccess = function() {
        console.log("User added:", user);
    };

    request.onerror = function() {
        console.log("Error adding user:", request.error);
    };
}

// Example usage:
addUser(1, "Alice", 25);

3. Updating Data in IndexedDB

Updating data is similar to adding, but we use put() instead of add(). The put() method replaces an existing record if the key already exists.

function updateUser(id, newName, newAge) {
    let transaction = db.transaction(["users"], "readwrite");
    let store = transaction.objectStore("users");

    let user = { id: id, name: newName, age: newAge };

    let request = store.put(user);

    request.onsuccess = function() {
        console.log("User updated:", user);
    };

    request.onerror = function() {
        console.log("Error updating user:", request.error);
    };
}

// Example usage:
updateUser(1, "Alice Johnson", 26);

Summary

  • Use add() to insert new data into IndexedDB.
  • Use put() to update existing data in IndexedDB.
  • Transactions must be in "readwrite" mode when modifying data.

Try Your Hand: Modify the updateUser function to check if the user exists before updating.