CRUD Operations Using IndexedDB
Learn how to perform CRUD operations on the IndexedDB’s object stores.
We'll cover the following...
We'll cover the following...
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
keyPathwhile creating the object store, we’ll need to pass a key when we add the data.
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 thetransactionto get a reference to the object store. - Line 9: Define a
newUserobject to store in the object store. This object has anidattribute set as thekeyPathvalue