Search⌘ K
AI Features

CRUD Operations Using IndexedDB

Explore how to manage data offline with IndexedDB in this lesson. Learn to add, retrieve, update, and delete data using object stores, transactions, and key handling. Gain practical knowledge on handling success and error events for CRUD actions and implement a basic app to test your IndexedDB skills within PWAs.

Adding data to an object store

Once we’ve created an object store, we can add data. This is done using the add method on the object store. This method takes the following two parameters:

  • The data we want to add.
  • The optional key. If we don’t specify a keyPath while creating the object store, we’ll need to pass a key when we add the data.
Node.js
request.onsuccess = function(event) {
console.log("Success! Database is now open.");
let db = event.target.result;
let storeName = "myObjectStore";
let transaction = db.transaction(storeName, "readwrite");
let myObjectStore = transaction.objectStore(storeName);
let newUser = {id: 1, name: "John Doe", age: 35};
addData(myObjectStore, newUser);
};
function addData(objectStore, data) {
var request = objectStore.add(data);
request.onsuccess = function(event) {
console.log("Data added!");
};
}

In the onsuccess event, start a transaction using the db.transaction() method. This method takes the following two parameters: the name of the object store we want to add data to and the mode of the transaction (here readwrite so we can add data)

  • Line 7: Use the objectStore() method on the transaction to get a reference to the object store.
  • Line 9: Define a newUser object to store in the object store.
...