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
keyPathwhile creating the object store, we’ll need to pass a key when we add the data.
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.