Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
IndexedDB
3.
IndexedDB characteristics
4.
IndexedDB operations
4.1.
Opening a connection to a database and Creating object-store
4.2.
Inserting data into object-store
4.3.
Retrieving data from an object store
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

IndexedDB

Author Malay Gain
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

IndexDB is a large-scale database built into the browser that allows storing data as key-value pairs. IndexedDB is more powerful than local storage as it can store large amounts of data without a persistent internet connection. IndexedDB is primarily useful for applications that can work in offline mode. Here we will be discussing the characteristics of IndexedDB and the basic operations that it can perform on this transactional database.

IndexedDB

IndexedDB is a javascript-based object-oriented database that works as client-side storage of a significant amount of data in a browser. IndexedDB store and retrieve data that are indexed with a key.

IndexedDB API uses these indexes for high-performance searches of this data. For using IndexedDB, we need to specify database schema, open a connection to the database and then retrieve and update the data with a series of transactions.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

IndexedDB characteristics

  • IndexedDB consists of the following structural components.
  1. Databases: It is the highest level of IndexedDB that contains one or object stores. IndexedDB can have one or more databases, but one database per web application will be.
  2. Object Store: The object store is a bucket that one can use to store data with associated indexes. It contains records stored as key-value pairs. It is similar to the table in a SQL database.
  3. Indexes: Indexes help to query data in the database by properties of the objects.
  • IndexedDB maintains the transactional model that ensures data integrity in the database.
  • IndexedDB operations are primarily asynchronous.
  • IndexedDB follows the same-origin policy. Each origin has its own set of databases. An origin is a domain, protocol, and port of a URL document. One origin can't access data from another origin.

http://www.google.com and https://www.google.com are not exact origins as their protocols are different (HTTP and HTTPS).

  • It can store large amounts of data without a persistent internet connection. For example, Google docs use indexedDB for storing a cached document in the browser and synchronizes with the server once in a while.

IndexedDB operations

Opening a connection to a database and Creating object-store

Opening a database is an asynchronous operation. We need to send a request to extend our database and then listen for events to know when it's ready. We'll open a Demo DB. If it doesn't exist yet then it will get created when we send the request. The two below say we're asking for version 2 of our database where only one version exists at any time, but one can use the version number to upgrade old data; as we'll see -

var db = null, // This is their to be used once we have our database
 request = window.indexedDB.open("DemoDB", 2);
// This listens for the successful opening of the db and will be called after the 'onupgradeneeded' util runs, if it does at all
request.onsuccess = function() {
 db = request.result; // then we have an access to our database!
 doThingsWithDB(db);
};

// But if our database didn't exist before, or it was an older version than what we requested,
// the `onupgradeneeded` event will be fired.

// We can use this to set up a new database and upgrade an old one with new object store

request.onupgradeneeded = function(event) {
 db = request.result;
 // If the 'oldVersion' var is less than 1 then it depicts that the database didn't exist. Let's set it up
 if (event.oldVersion < 1) {
 // We'll create a new "things" store with `autoIncrement`ing keys
 var store = db.createObjectStore("things", { autoIncrement: true });
 }

 // In version 2 of our database, we are creating a new index same as the name of each item
 if (event.oldVersion < 2) {
 // Let's load the object store and create an index
 var store = request.transaction.objectStore("things");
 store.createIndex("by_name", "name");
 }
};

// Handle any errors
request.onerror = function() {
 console.error("Something went wrong when we tried to request the database!");
};

Inserting data into object-store

Anything which needs to happen with data in an Indexed DB database occurs in a transaction. Here we will see how to 

// Here, to create a new transaction; we'll use the default "read-only" mode, and the things store
var transaction = db.transaction(["things"]);
// Transactions use events such as database open requests. Let's listen for success
transaction.oncomplete = function() {
 console.log("All done!");
};
// And make sure we handle errors
transaction.onerror = function() {
 console.log("Something went wrong with our transaction: ", transaction.error);
};
// Now since everything is set up, let's get our things stored and load some objects!
var store = transaction.objectStore("things");
// We'll load the coffee_cup object which we added in Adding objects
var request = store.get("coffee_cup");
// Let's open a listener so that we can check whether everything works
request.onsuccess = function(event) {
 // All done, let's log our object to the console
 console.log(request.result);
};
// That was a lengthy util for a basic retrieval and if one just wanted to get
// a single object and doesn't care about errors, then it can shorten things a lot
db.transaction("things").objectStore("things")
 .get("coffee_cup").onsuccess = e => console.log(e.target.result);

Retrieving data from an object store

We'll use the utils that we set up in Opening a database for retrieving data. See the below snippets for a better understanding.

// Here, to create a new transaction, we'll use the default "readonly" mode and the things store
var transaction = db.transaction(["things"]);
// Transactions generally use events, just like database open requests. Let's listen for success
transaction.oncomplete = function() {
 console.log("All done!");
};
// And make sure we handle errors
transaction.onerror = function() {
 console.log("Something went wrong with our transaction: ", transaction.error);
};
// Now that everything is set, let's get our things to store and load some objects!
var store = transaction.objectStore("things");
// Here we'll load the 'coffee_cup' object we added in Adding objects
var request = store.get("coffee_cup");


// Let's open a  listener so we can check whether everything worked
request.onsuccess = function(event) {
 // All set, let's try logging our object to the console
 console.log(request.result);
};
// That was pretty lengthy util for a basic retrieval task. If one just wants to get
// a single object and is willing to ignore the errors, then they can shorten things a lot
db.transaction("things").objectStore("things")
 .get("coffee_cup").onsuccess = e => console.log(e.target.result);

FAQs

1. What is an IndexedDB?

IndexedDB is a javascript-based object-oriented database that works as client-side storage of a significant amount of data in a browser. IndexedDB store and retrieve data that are indexed with a key. The IndexedDB API uses these indexes for high-performance searches of this data. 

2. When should one use an indexedDB vs the local storage?

One should generally go by using an IndexedDB for storing extensive data in the browser. In contrast, they should use the LocalStorage for small amounts of data that one needs synchronous access to.

Key Takeaways

This article covered what IndexedDB is and how it works in the browser.

Check out the Coding Ninjas Studio library to better grasp the data structures and algorithms and the guided path for learning javascript from basics.

Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here. 

Happy learning!

Previous article
Service Workers
Next article
Window.postMessage()
Live masterclass