Using IndexedDB: removing data

Using IndexedDB: removing data from an object store

Let’s move to the next online example at JSBin:

devtools show that a customer has been removed once clicked on the remove customer button

See the changes in Chrome dev. tools: refresh the view (right click/refresh) or press F12 or cmd-alt-i twice. There is a bug in the refresh feature with some versions of Google Chrome.

How to try the example:

    1. Be sure to click the “create database button” to open the existing database.
    2. Then use Chrome dev tools  to check that the customer with ssn=444-44-444 exists. If it’s not there, just insert into the database like we did earlier in the course.
    3. Right click on indexDB in the Chrome dev tools and refresh the display of the IndexedDB’s content if necessary if you cannot see customerwith ssn=444-44-444. Then click on the “Remove Customer ssn=444-44-4444(Bill)” button. Refresh the display of the database. The ‘Bill’ object should have disappeared!

Code added in this example:

  1. function removeACustomer() {
  2.    if(db === null) {
  3.       alert(‘Database must be opened first, please click the
  4.              Create 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=” +
  14.                    event.target.error.name);
  15.    };
  16.    var objectStore = transaction.objectStore(“customers”);
  17.    alert(‘removing customer ssn=444-44-4444’);
  18.    var request = objectStore.delete(“444-44-4444”);
  19.    request.onsuccess = function(event) {
  20.       console.log(“Customer removed.”);
  21.    };
  22.    request.onerror = function(event) {
  23.       alert(“request.onerror, could not remove customer, errcode
  24.             = “ + event.target.error.name + “. The ssn does not
  25.             exist in the Database”);
  26.    };
  27. }

Notice that after the deletion of the Customer (line 23), the request.onsuccess callback is called. And if you try to print the value of the event.target.result variable, it is “undefined“.

Short way of doing the delete:

It is also possible to shorten the code of the above function a lot by concatenating the different operations (getting the store from the db, getting the request, calling delete, etc.). Here is the short version:

  1. var request = db.transaction([“customers”], “readwrite”)
  2. .objectStore(“customers”)
  3. .delete(“444-44-4444”);

Leave a comment