Using IndexedDB: modifying data

Using IndexedDB: modifying data from an object store

We used request.add(object) to add a new customer and request.delete(keypath) to remove a customer. Now, we will use request.put(keypath) to update a customer!

Online example at JSBin:

devtools show a customer being updated in IndexedDB

The above screenshot shows how we added an empty customer with ssn=””, (we just clicked on the open database button, then on the “add a new customer button” with an empty form).

Now, we fill the name, age and email input fields to update the object with ssn=”” and click on the “update data about an existing customer” button. This updates the data in the object store, as shown in this screenshot:

devtools show updated customer

Here is the new code added to our example:

  1. function updateACustomer() {
  2.    if(db === null) {
  3.      alert(‘Database must be opened first, please click the Create
  4.             CustomerDB Database first’);
  5.      return;
  6.    }
  7.    var transaction = db.transaction([“customers”], “readwrite”);
  8.    // Do something when all the data is added to the database.
  9.    transaction.oncomplete = function(event) {
  10.      console.log(“All done!”);
  11.    };
  12.    transaction.onerror = function(event) {
  13.      console.log(“transaction.onerror errcode=” + event.target.error.name);
  14.    };
  15.    var objectStore = transaction.objectStore(“customers”);
  16.    var customerToUpdate={};
  17.    customerToUpdate.ssn = document.querySelector(“#ssn”).value;
  18.    customerToUpdate.name = document.querySelector(“#name”).value;
  19.    customerToUpdate.age = document.querySelector(“#age”).value;
  20.    customerToUpdate.email = document.querySelector(“#email”).value;
  21.    alert(‘updating customer ssn=’ + customerToUpdate.ssn);
  22.    var request = objectStore.put(customerToUpdate);
  23.    request.onsuccess = function(event) {
  24.      console.log(“Customer updated.”);
  25.    };
  26.    request.onerror = function(event) {
  27.      alert(“request.onerror, could not update customer, errcode= “ +
  28.         event.target.error.name + “. The ssn is not in the
  29.         Database”);
  30.   };
  31. }

The update occurs at line 28.

Leave a comment