Javascript in 100 bits

Course by zooboole,

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

Lesson 59 - Adding Data to IndexedDB

Now that we have created an IndexedDB database, it's time to learn how to add data to it. IndexedDB allows us to store key-value pairs where the values can be objects.

Steps to Add Data to IndexedDB

1. Open the Database

Before adding data, ensure the database is opened successfully.

2. Start a Transaction

All read and write operations in IndexedDB happen inside transactions.

3. Get the Object Store

The object store is where data is stored in IndexedDB.

4. Use the add Method

The add method is used to insert new data.

Example Code

// Open the database
let request = indexedDB.open("MyDatabase", 1);

request.onsuccess = function(event) {
    let db = event.target.result;

    // Start a transaction
    let transaction = db.transaction("Users", "readwrite");

    // Get the object store
    let store = transaction.objectStore("Users");

    // Data to add
    let user = { id: 1, name: "John Doe", age: 30 };

    // Add the data
    let addRequest = store.add(user);

    addRequest.onsuccess = function() {
        console.log("Data added successfully!");
    };

    addRequest.onerror = function() {
        console.log("Error adding data.");
    };
};

Explanation

  1. We open the database and start a transaction.
  2. We get access to the "Users" object store.
  3. We define a user object with an id, name, and age.
  4. We use the add() method to store the object.
  5. If successful, we log a success message; otherwise, we handle errors.

Try Your Hand

Modify the above code to:

  • Add multiple users to the object store.
  • Log all added users in the console.