What Is IndexedDb And How To Use It

What Is IndexedDb And How To Use It

What is IndexedDB?

 
The IndexedDb (Indexed database) is a Javascript application programming interface provided by web browsers for managing NoSQL database of JSON objects. It is a standard maintained by the World Wide Web Consortium. As an alternative to localStorage, IndexedDB can provide more storage capacity and can store more data as compared to local storage.
 

When to use IndexedDB?

 
IndexedDB is used in different scenarios and depends on the developer's needs. Mostly it is used to store data that is not likely to be changed again and again or meta data is stored in IndexedDB. For example you can store some data of a logged in user in Indexed db as he logged in and in an application you can use it according to your need. One more use is to store permission details of loggedin user in indexedDB.
 

Creating IndexedDB

 
Follow the following steps to create an IndexedDB,
 
First of all we will create a simple html file that will have a button to create a new IndexedDB. For that, create a HTML file and add following code,
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <body>  
  5.     <button id="btnCreateStore" onclick="initDB()">Initialize Database</button>  
  6.     <p id="result"></p>  
  7.     <div id="UsersContainer" style="display: none;">  
  8.         <button id="btnShowUsers" onclick="showUsers()">Show Users</button>  
  9.         <p>  
  10.             <input type="text" id="txtName">  
  11.             <input type="text" id="txtEmail">  
  12.             <input type="text" id="txtCountry">  
  13.             <button type="button" onclick="addUser()">Add</button>  
  14.         </p>  
  15.         <div id="UsersTable">  
  16.   
  17.         </div>  
  18.     </div>  
  19. </body>  
  20.   
  21. </html>  
Next step is to create and initialize IndexedDB when you click on the  Initialize Database button. For that, create a script tag in the html file and add the following function,
  1. var friends_Data = [  
  2.             { EmployeeName: "Jamil Moughal", EmployeeEmail: "jamil@gmail.com", Country: "Pakistan" },  
  3.             { EmployeeName: "Diviya", EmployeeEmail: "diviya@gmail.com", Country: "India" },  
  4.             { EmployeeName: "Ali Khan", EmployeeEmail: "alikhan@gmail.com", Country: "Egypt" },  
  5.             { EmployeeName: "John Charles", EmployeeEmail: "john@gmail.com", Country: "United States" },  
  6.             { EmployeeName: "Steve", EmployeeEmail: "steve@gmail.com", Country: "Germany" },  
  7.         ];  
  8.   
  9.         function initDB() {  
  10.             var Database_Name = "UsersDB";  
  11.             var DB_Version = "1.0";  
  12.             var dbObj;  
  13.             var request = indexedDB.open(Database_Name, DB_Version)  
  14.             request.onsuccess = function (e) {  
  15.                 document.getElementById("result").innerHTML = "Database Opened :)";  
  16.                 dbObj = request.result;  
  17.                 document.getElementById('UsersContainer').style.display = 'block';  
  18.             }  
  19.             request.onerror = function (e) {  
  20.                 console.log("Error:" + e.target.errorCode)  
  21.                 document.getElementById("result").innerHTML = "Error! The Database connection not opened. Please See The Log";  
  22.             }  
  23.             request.onupgradeneeded = function (e) {  
  24.   
  25.                 var objectStore = e.currentTarget.result.createObjectStore("MyObjectStore", { keyPath: "id", autoIncrement: true });  
  26.   
  27.                 //creating Indexes      
  28.                 objectStore.createIndex("EmployeeName""EmployeeName", { unique: false });  
  29.                 objectStore.createIndex("EmployeeEmail""EmployeeEmail", { unique: true });  
  30.                 objectStore.createIndex("Country""Country", { unique: false });  
  31.   
  32.                 //To store the Data      
  33.                 for (i in friends_Data) {  
  34.                     objectStore.add(friends_Data[i]);  
  35.                 }  
  36.             };  
  37.         }  
After this, refresh your html file and click on Initialize Database button, then open your browser console and click on Application window. You will see the IndexedDB, in the database above records will be present. It will look as follows,
 
What Is IndexedDb And How To Use It
 
Database is created in IndexedDB storage named as UsersDB. It also has a Store named as MyObjectStore which have all the records that we have added. Now we will get all records from the IndexedDB storage. We will do this when clicking on Show Users button. Add the following function in your code.
  1. function showUsers() {  
  2.     var Database_Name = "UsersDB";  
  3.     var DB_Version = "1.0";  
  4.   
  5.     var request = window.indexedDB.open(Database_Name, DB_Version)  
  6.     var db;  
  7.     request.onsuccess = function (e) {  
  8.         db = e.target.result;  
  9.         var transaction = db.transaction("MyObjectStore""readwrite");  
  10.         var objectStore = transaction.objectStore("MyObjectStore");  
  11.   
  12.         var emp_name = "";  
  13.   
  14.         var add_request = objectStore.getAll()  
  15.         add_request.onsuccess = function (e) {  
  16.             var list = e.target.result;  
  17.             var _html = "";  
  18.             if (list != undefined && list.length > 0) {  
  19.                 for (let index = 0; index < list.length; index++) {  
  20.                     _html += "<p>";  
  21.                     _html += 'EmployeeName: <strong>' + list[index].EmployeeName + '</strong>Email:<strong>' + list[index].EmployeeEmail + '</strong>Country:<strong>' + list[index].Country + '</strong>';  
  22.                     _html += '<button type="button" onclick="deleteUser(' + list[index].id + ')" style="background: red; color: white;">Delete</button>';  
  23.                     _html += '</p>';  
  24.                 }  
  25.             }  
  26.             document.getElementById('UsersTable').innerHTML = _html;  
  27.             // do something when the add succeeded                                
  28.         };  
  29.         transaction.oncomplete = function (e) {  
  30.             // do something after the transaction completed        
  31.         };  
  32.         transaction.onabort = function (e) {  
  33.             // do something after the transaction aborted       
  34.         };  
  35.         transaction.onerrort = function (e) {  
  36.             // do something after the transaction canceled      
  37.         };
  38.     }  
  39. }  
After adding code, save and refresh the file and click on Show Users button. Your screen will look as,
 
What Is IndexedDb And How To Use It
 
We have successfully created a new Database in IndexedDB and have added some dummy data for testing. Now we will add data by user action. When user will add data in textboxes and press the Add button, data from textboxes should be added in database. For this add the following function in your code,
  1. function addUser() {  
  2.     var Database_Name = "UsersDB";  
  3.     var DB_Version = "1.0";  
  4.   
  5.     var request = window.indexedDB.open(Database_Name, DB_Version)  
  6.     var db;  
  7.     request.onsuccess = function (e) {  
  8.         db = e.target.result;  
  9.         var transaction = db.transaction("MyObjectStore""readwrite");  
  10.         var objectStore = transaction.objectStore("MyObjectStore");  
  11.         var add_request = objectStore.add({ EmployeeName: 'Good Boy', EmployeeEmail: "email@email.com", Country: "Austria" });  
  12.         add_request.onsuccess = function (e) {  
  13.             // do something when the add succeeded                                
  14.         };  
  15.         transaction.oncomplete = function (e) {  
  16.             // do something after the transaction completed        
  17.         };  
  18.         transaction.onabort = function (e) {  
  19.             // do something after the transaction aborted       
  20.         };  
  21.         transaction.onerrort = function (e) {  
  22.             // do something after the transaction canceled      
  23.         }; 
  24.     }  
  25. }  
When you will click on Add button a new entry will be added in your IndexedDB storage. Now we will learn how we can delete some specific record in the database. For this, add the following function in your code.
  1. function deleteUser(Id) {  
  2.     var Database_Name = "UsersDB";  
  3.     var DB_Version = "1.0";  
  4.   
  5.     var request = window.indexedDB.open(Database_Name, DB_Version)  
  6.     var db;  
  7.     request.onsuccess = function (e) {  
  8.         db = e.target.result;  
  9.         var transaction = db.transaction("MyObjectStore""readwrite");  
  10.         var objectStore = transaction.objectStore("MyObjectStore");  
  11.   
  12.        
  13.         var request = db.transaction("MyObjectStore""readwrite")  
  14.             .objectStore("MyObjectStore")  
  15.             .delete(Id);  
  16.         request.onsuccess = function (event) {  
  17.             // It's gone!  
  18.         };  
  19.   
  20.     }  
  21. }  
Now we are done with our things. We have learned how IndexedDb is created, how data is retrieved and how records can be removed. 
 
Thank you.
 
Happy Coding