Storing Data to the Object Store

Learn to add data to the object store.

To add data to a data store in IndexedDB, we need to follow these steps:

  1. Open a database.

  2. Create an object store.

  3. Start a transaction.

  4. Add the data to the object store using the add() method.

Till now, we know how to open a database and create an object store. Let’s see how to start a transaction and add data to the object store.

Start a transaction

To add data to a database, we need to create transactions. A transaction is a unit of work that makes changes to the database. To create a transaction, we should use the syntax below:

db.transaction(store[, type]);
Syntax to create a transaction

We can use the transaction() method of the IDBDatabase object. The method accepts as arguments an array with the list of stores and the typereadonly or readwrite of the transaction.

The code below demonstrates how to create a transaction:

Press + to interact
let dbOpenRequest = indexedDB.open('School_add_data_demo', 1);
let db;
dbOpenRequest.onsuccess = function() {
db = dbOpenRequest.result;
// Create the transaction for the Student object store in read-write mode
let transaction = db.transaction(['Student'], 'readwrite');
};

In the code above: ...