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 a 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, depending on the developer's needs. Mostly, it is used to store data that is not likely to be changed again and again, or metadata is stored in IndexedDB. For example, you can store some data of a logged-in user in an Indexed db as he logged in, and it in an application you can use it according to your need. One more use is to store permission details of logged-in users 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 an HTML file and add the following code.

<!DOCTYPE html>
<html>

<body>
    <button id="btnCreateStore" onclick="initDB()">Initialize Database</button>
    <p id="result"></p>
    <div id="UsersContainer" style="display: none;">
        <button id="btnShowUsers" onclick="showUsers()">Show Users</button>
        <p>
            <input type="text" id="txtName">
            <input type="text" id="txtEmail">
            <input type="text" id="txtCountry">
            <button type="button" onclick="addUser()">Add</button>
        </p>
        <div id="UsersTable">
        </div>
    </div>
</body>

</html>

The next step is to create and initialize IndexedDB by clicking on the Initialize Database button. For that, create a script tag in the html file and add the following function.

var friends_Data = [
    { EmployeeName: "Jamil Moughal", EmployeeEmail: "[email protected]", Country: "Pakistan" },
    { EmployeeName: "Diviya", EmployeeEmail: "[email protected]", Country: "India" },
    { EmployeeName: "Ali Khan", EmployeeEmail: "[email protected]", Country: "Egypt" },
    { EmployeeName: "John Charles", EmployeeEmail: "[email protected]", Country: "United States" },
    { EmployeeName: "Steve", EmployeeEmail: "[email protected]", Country: "Germany" },
];

function initDB() {
    var Database_Name = "UsersDB";
    var DB_Version = "1.0";
    var dbObj;
    var request = indexedDB.open(Database_Name, DB_Version);
    
    request.onsuccess = function (e) {
        document.getElementById("result").innerHTML = "Database Opened :)";
        dbObj = request.result;
        document.getElementById('UsersContainer').style.display = 'block';
    };
    
    request.onerror = function (e) {
        console.log("Error:" + e.target.errorCode);
        document.getElementById("result").innerHTML = "Error! The Database connection not opened. Please See The Log";
    };
    
    request.onupgradeneeded = function (e) {
        var objectStore = e.currentTarget.result.createObjectStore("MyObjectStore", { keyPath: "id", autoIncrement: true });
        
        // Creating Indexes
        objectStore.createIndex("EmployeeName", "EmployeeName", { unique: false });
        objectStore.createIndex("EmployeeEmail", "EmployeeEmail", { unique: true });
        objectStore.createIndex("Country", "Country", { unique: false });
        
        // Storing the Data
        for (i in friends_Data) {
            objectStore.add(friends_Data[i]);
        }
    };
}

After this, refresh your html file and click on the Initialize Database button, then open your browser console and click on the 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

The database is created in IndexedDB storage and is named UsersDB. It also has a Store named MyObjectStore, which has all the records that we have added. Now, we will get all records from the IndexedDB storage. We will do this when clicking on the Show Users button. Add the following function in your code.

function showUsers() {
    var Database_Name = "UsersDB";
    var DB_Version = "1.0";

    var request = window.indexedDB.open(Database_Name, DB_Version);
    var db;

    request.onsuccess = function (e) {
        db = e.target.result;
        var transaction = db.transaction("MyObjectStore", "readwrite");
        var objectStore = transaction.objectStore("MyObjectStore");

        var emp_name = "";

        var add_request = objectStore.getAll();
        add_request.onsuccess = function (e) {
            var list = e.target.result;
            var _html = "";

            if (list != undefined && list.length > 0) {
                for (let index = 0; index < list.length; index++) {
                    _html += "<p>";
                    _html += 'EmployeeName: <strong>' + list[index].EmployeeName + '</strong>';
                    _html += 'Email:<strong>' + list[index].EmployeeEmail + '</strong>';
                    _html += 'Country:<strong>' + list[index].Country + '</strong>';
                    _html += '<button type="button" onclick="deleteUser(' + list[index].id + ')" style="background: red; color: white;">Delete</button>';
                    _html += '</p>';
                }
            }

            document.getElementById('UsersTable').innerHTML = _html;
        };

        transaction.oncomplete = function (e) {
            // do something after the transaction completed
        };
        
        transaction.onabort = function (e) {
            // do something after the transaction aborted
        };
        
        transaction.onerror = function (e) {
            // do something after the transaction canceled
        };
    };
}

After adding code, save and refresh the file and click on the 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 the user adds data in textboxes and presses the Add button, data from textboxes should be added in to database. For this, add the following function in your code.

function addUser() {
    var Database_Name = "UsersDB";
    var DB_Version = "1.0";

    var request = window.indexedDB.open(Database_Name, DB_Version);
    var db;

    request.onsuccess = function (e) {
        db = e.target.result;
        var transaction = db.transaction("MyObjectStore", "readwrite");
        var objectStore = transaction.objectStore("MyObjectStore");

        var add_request = objectStore.add({
            EmployeeName: 'Good Boy',
            EmployeeEmail: "[email protected]",
            Country: "Austria"
        });

        add_request.onsuccess = function (e) {
            // do something when the add succeeded
        };

        transaction.oncomplete = function (e) {
            // do something after the transaction completed
        };

        transaction.onabort = function (e) {
            // do something after the transaction aborted
        };

        transaction.onerror = function (e) {
            // do something after the transaction canceled
        };
    };
}

When you will click on Add button a new entry will be added in your IndexedDB storage. Now, we will learn how to delete some specific records in the database. For this, add the following function in your code.

function deleteUser(Id) {
    var Database_Name = "UsersDB";
    var DB_Version = "1.0";

    var request = window.indexedDB.open(Database_Name, DB_Version);
    var db;

    request.onsuccess = function (e) {
        db = e.target.result;
        var transaction = db.transaction("MyObjectStore", "readwrite");
        var objectStore = transaction.objectStore("MyObjectStore");

        var delete_request = objectStore.delete(Id);

        delete_request.onsuccess = function (event) {
            // It's gone!
        };
    };
}

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