How to use IndexedDB to build Progressive Web Apps

About indexedDB :

IndexedDB is a large-scale, NoSQL storage system that is built into a web browser.It is much more powerful than localStorage.

  • It Supports transactions for reliability.
  • It Stores almost any kind of values by keys.
  • It Can store much bigger volumes of data than localStorage.
  • It Supports key range queries, indexes.

Use Of  indexedDB ?

It’s useful for applications that store a large amount of data and don’t need a persistent internet connection.

IndexedDB allows you to create web applications that can work both online and offline.

For example, Google Docs uses the IndexedDB to store the cached documents in the browser and synchronizes with the server once in a while. This allows Google Docs to increase performance while enhancing user experiences.

Structure Of IndexedDB:

The following picture illustrates the structure of the IndexedDB:

Basic IndexedDB concepts

The following briefly introduces the basic concepts in the IndexedDB:

  • IndexedDB databases store key-value pairs
  • IndexedDB is transactional
  • IndexedDB API is mostly asynchronous
  • IndexedDB is a NoSQL system
  • IndexedDB follows the same-origin policy

Object Store

To store something in IndexedDB, we need an object store.

An object store is a core concept of IndexedDB. Counterparts in other databases are called “tables” or “collections”. It’s where the data is stored. A database may have multiple stores: one for users, another one for goods, etc.

Despite being named an “object store”, primitives can be stored too.

There must be a unique key for every value in the store.

A key must be one of these types – number, date, string, binary, or array. It’s a unique identifier, so we can search/remove/update values by the key.

The following are the basic steps for doing something in IndexedDB.

  1. Open a database.
  2. Create an object store in the database.
  3. Start a transaction and make a request to do some database operation, like adding or retrieving data.
  4. Wait for the operation to complete by listening for the right kind of DOM event.
  5. Do something with the results (which can be found on the request object).

First, we open a database using .open(dbName, versionInt) method. This sends an open request to the IndexedDB database and returns the request object. This method accepts the database name and version number of the database.

If the database doesn’t exist, then it will be created. If the database exists but the version number is higher, then the database is upgraded with the new version without keeping a copy of the older version.

var request = self.IndexedDB.open('EXAMPLE_DB', 1); 
var db; request.onsuccess = function(event) { 
console.log('[onsuccess]', request.result);
db = event.target.result; // === request.result }; 
request.onerror = function(event) { 
console.log('[onerror]', request.error); };

You can run the above code in the browser and look up for the database in Chrome Developers Tools, inside the Application > IndexedDB tab. Since we don’t have any data in our database now, it is shown empty.

The object store can be created using the createObjectStore method on the database object.  The syntax for the createObjectStore method is as follows.

db.createObjectStore(storeName, options);

Store name (storeName) must be unique.

Let’s create a sample object store for our database.

request.onupgradeneeded = function(event) {
    var db = event.target.result;
    var store = db.createObjectStore('products', {keyPath: 'id'});
};

With the above code, we are creating a products object store to store JavaScript objects. These objects will have a key id which will be the key used by the object store to locate objects.

To insert or do any operations on database, we need to get the transaction object from the database. That can be done by using the transaction method in the database with one of the following signatures.

var transaction = db.transaction(storeName, mode);
var transaction = db.transaction(storeNamesArray, mode);

In the above syntax, the first parameter is the name of the object store or the array of names of the object stores. If you specify the array of store names, then you get permission to perform database operations on multiple stores.

For now, we are going to use add method to put some data in products object store whose transaction we have already acquired.

var request = self.IndexedDB.open('EXAMPLE_DB', 1);
request.onsuccess = function(event) {
    // some sample products data
    var products = [
        {id: 1, name: 'Red Men T-Shirt', price: '$3.99'},
        {id: 2, name: 'Pink Women Shorts', price: '$5.99'},
        {id: 3, name: 'Nike white Shoes', price: '$300'}
    ];
// get database from event
    var db = event.target.result;
// create transaction from database
    var transaction = db.transaction('products', 'readwrite');
// add success event handleer for transaction
    // you should also add onerror, onabort event handlers
    transaction.onsuccess = function(event) {
        console.log('[Transaction] ALL DONE!');
    };
// get store from transaction
    // returns IDBObjectStore instance
    var productsStore = transaction.objectStore('products');
// put products data in productsStore
    products.forEach(function(product){
        var db_op_req = productsStore.add(product); // IDBRequest
    });
};

You should again check the database in Chrome Developer Tools, which should appear like below.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories