Still Remember IndexedDB?
Tags: javascript, webdev, html, database
Published: 2022-07-13 16:38:18

We remember that there was a browser storage called IndexedDB like web storage and cookie.

IndexedDB is a large-scale, NoSQL storage system. It lets you store just about anything in the user’s browser. In addition to the usual search, get, and put actions, IndexedDB also supports transactions.


In this article, we’ll focus on the following.

    -Why do we need IndexedDB?
    -How do we use an IndexedDB in our applications?
    -Features of IndexedDB
    -Limitations of IndexedDB
    -Is IndexedDB right for your applications?

**Why do we need IndexedDB?**

Indexed DB is considered more powerful than localStorage!

Do you know the reason behind it? Let’s find out.

**Can store much bigger volumes of data than localStorage**

There is no particular limit like in localStorage (between 2.5MB and 10MB). The maximum limit is based on the browser and the disk space. For example, Chrome and Chromium-based browsers allow up to 80% disk space. If you have 100GB, Indexed DB can use up to 80GB of space, and 60GB by a single origin. Firefox allows up to 2GB per origin while Safari allows up to 1GB per origin.

**Can store any kind of value based on { key: value } pairs**

Higher flexibility to store different data types. This means not only strings but also binary data (ArrayBuffer objects, Blob objects, etc.). It uses an object store to hold data internally.

**Provides lookup interfaces**

This is not available in other browser storage options such as localStorage and sessionStorage.

**Useful for web applications that don’t require a persistent internet connection**

IndexedDB can be very useful for applications that work both online and offline. For example, this can be used for client-side storage in Progressive Web Apps (PWAs).

**Application state can be stored**

By storing the application state for recurring users, the performance of your application can be increased drastically. Later on, the application can sync-up with the backend server and update the application via lazy loading.

Let’s have a look at the structure of the IndexedDB which can store multiple databases.

**How do we use Indexed DB in our applications?**

In the following section, we’ll look at how to bootstrap an application with IndexedDB.

**1. Open the database connection using “window.indexedDB"**


`const openingRequest = indexedDB.open('UserDB', 1);`

**2. Create object store**

Once the database connection is open, the onupgradeneeded event will be fired, which can be used to create object stores.

`// Create the UserDetails object store and indexesrequest.onupgradeneeded = (event) => {
     let db = event.target.result;

     // Create the UserDetails object store 
     // with auto-increment id
     let store = db.createObjectStore('UserDetails', {
         autoIncrement: true
     });

     // Create an index on the NIC property
     let index = store.createIndex('nic', 'nic', {
         unique: true
     });
 };`

### 
3. Insert data into the object store###

Once a connection is opened to the database, the data can be managed inside the onsuccess event handler. Inserting data happens in 4 steps.

`function insertUser(db, user) {
    // Create a new transaction
    const txn = db.transaction('User', 'readwrite');

    // Get the UserDetails object store
    const store = txn.objectStore('UserDetails');    // Insert a new record
    let query = store.put(user);

    // Handle the success case
    query.onsuccess = function (event) {
        console.log(event);
    };

    // Handle the error case
    query.onerror = function (event) {
        console.log(event.target.errorCode);
    }

    // Close the database once the transaction completes
    txn.oncomplete = function () {
        db.close();
    };
}`

Once the insertion function is created, the onsuccess event handler of the request can be used to insert more records.

`request.onsuccess = (event) => {
   const db = event.target.result;   insertUser(db, {
     email: 'john.doe@outlook.com',
     firstName: 'John',
     lastName: 'Doe',
   });   insertUser(db, {
     email: 'ann.doe@gmail.com',
     firstName: 'Ann',
     lastName: 'Doe'
   });
};`

There are many operations that can be performed on the IndexedDB. Some of them are as follows.

    -Read/search data from object stores by key
    -Read/search data from object stores by index
    -Update data of a record
    -Delete a record
    -Migrate from a previous version of a database, etc.

If you need insights about how to achieve the above, let me know in the comments section below. You can refer here for more information.

**Features of Indexed DB**

-Has an asynchronous API
-Supports transactions for reliability
-Supports versioning
-Private to domain

**Is IndexedDB right for your application?**

Based on the many features provided by IndexedDB, the answer to this million-dollar question could be Yes! However, before jumping to a conclusion, ask yourself the following questions.

-Does your application require offline access?
-Do you need to store a large amount of data on the client-side?
-Do you need to quickly locate/search data in a large set of data?
-Does your application access the client-side storage using the supported browsers by IndexedDB?
-Do you need to store various types of data including JavaScript objects?
-Does writing/reading from client-side storage need to be non-blocking?

If the answer to all of the above questions is Yes, IndexedDB is the best option for you. But if such functionality is not required, you might as well choose a storage method such as localStorage because it provides widespread browser adoption and features an easy-to-use API.