IndexedDB, a client side Database

Madhav Mansuriya
6 min readJul 25, 2020

--

Do you really need cache ? or what if i say you can have Data Base on client side itself

Yes you heard it correct, now you can have database on client side it self, you no more need to store your data in cache of browser

What is indexedDB ?

indexedDB is a client side DataBase, it stores data on the client end itself (in browser) as cache/local storage does. IndexedDB acts like a DB, it is NOSQL DataBase. Stores Data as an object, you can perform READ/ Write operation on the object.

Object are written and overwritten that are indexed with key: value pair as we do with the local storage. IndexedDB can store all kind of data that makes it different from local storage, in local storage you can only store string. The problem with local storage is that you need to stringify data while reading and writing , here you can get rid of that, store like and object, retrieve like an object. Talking about limitation of IndexedDB is that you can access the data in the same domain, i.e. if you store data on abc.com you will be able to retrieve data on the different page of same domain, if you try to access that data with different domain it is not possible. Local storage works synchronously while IndexedDB works asynchronously.

How does it works ?

but in the case of local storage, it is an extended object that you can access directly by querying on the key. IndexedDB doesn’t use row column format to store data as traditional database systems, so we don’t need SQL’s to retrieve data, and still evolving :D

Steps to Keep in Mind while using IndexedDB

  • open a DB
  • Create an object store (object store basically defines the structure of data, as we have tables in traditional DB)
  • specify key while defining DB
  • Query DB, on success of transaction request (async, so we need to check is it done or not)
  • close the transaction

Terminology used

  • Transaction: Transaction is the data request done to the DB (in traditional DB language we call it as query)
  • on success: onsuccess is the method that is used to check wether the data retrieval process is completed or not (as indexedDB is async)
  • object store: Object store refers to the structure of the data (in traditional DB language we call it as a table)

Methods used

  • opne() : opne method is used with the Database instance to open the database connection ex: db.open()
  • onsuccess(): this method is used to check the DB connection that we were trying to do was that successful or not
  • onerror(): this will help to catch any error, while trying to connect DB
  • onupgradeneeded(): this is the method fired when a new DB is opened or the same DB is opened with the new version, main purpose of this method is to initialise objectstore

Lets play with code:

Step 1: check if indexedDB support is available in browser or not :D

some of the fields that we are going to use in this example

these are object keys used in the below example s_id, s_name, s_class, s_age

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;if (!window.indexedDB) {   console.error("opps!!!! indexed db is not supported in your    browser");}

Step 2: Initialise variables globally that will be used

// opening a new DB and declaring other variableslet request = window.indexedDB.open("myDb", 1),db, //for creating a db instancetx, //for creating a transaction instancestore, //definfig a pattern in which data will be stored this is just like tableindex; //for adding index to the records

to open a new db window.indexedDB.open(“myDb”, 1)

.open() method is used, which has 2 params. 1st param is the name of the DB and 2nd is the version of DB, you can have infinite version of your DB

Step 3: onupgradeneeded method, helps to initialise object store

// this function will be get executed when any new DB is opened or DB is opened for the first time or the same DB is opened with the new versionrequest.onupgradeneeded = function (event) {console.log("new DB or Db with the new version is opened");let db = request.result;// creating a object store, table in the language of traditional db language// createobjectstore <- this method will take 2 params// 1 -> name of the object store, 2 -> primary key (can be auto increment or, the field from the table itself)store = db.createObjectStore("students", {keyPath: "s_id"});// or -> autoincrement// store = createobjectstore("students", {autoIncrement: true});// setting up index in the DB// index can be created on any field we will chosse s_name// s_name can be redundant so we can have index on that and can search student quickly with the help of index// will take 3 params/*** 1st param = s_name is the index name* 2nd param = s_name is the key in the database* 3rd param = unique, that specifies that the column which is indexed will not be having unique values*/let index = store.createIndex("s_name", "s_name", {unique: false})};

Creating a DB store

store = db.createObjectStore("students", {keyPath: "s_id"});

this takes 2 params, dbstore name (object name) in traditional db language we can say it as a table name, and the second params is primary key

object stores can kay autoIncrement as a primary key

store = db.createObjectStore("students", {autoIncrement: true});

or you can have both

store = db.createObjectStore("students", {keyPath: "s_id", autoIncrement: true});

this will have primary key as autoIncrement value and key path as s_id

indexing in DB

let index = store.createIndex(“s_name”, “s_name”, {unique: false})

we can have indexing in the DB for fast searching, defining index on s_name column, here unique: false means s_name field will have redundant values

Step 4: Catching error if any, while creating object store and establishing connections

request.onerror = function (error) {console.error("\n\n\n error : ", error)};

Step 5: onsuccess, when the db connection is done and object store is created successfully

request.onsuccess = function (event) {console.log("\n\n\n DB created successfully");// initializing the DB variabledb = request.result;// giving permission to transaction on the particular databasetx = db.transaction("students", "readwrite");// store is the structure of the data that is to be stire in the databasestore = tx.objectStore("students");// specifing the indexindex = store.index("s_name");// adding general error handler to track the error while performing the trnasactionsdb.onerror = function (error) {console.error("tx error = ", error);}// retriving data from DBlet data = store.get("s1"); //getting data by keydata.onsuccess = function () {console.log(data.result);}let data2 = index.get("Madhav Mansuriya"); //getting data by indexdata2.onsuccess = function () {console.log(data2.result.s_age);}tx.oncomplete = function () {db.close();}};

db = request.result; initialising DB with the request result

tx = db.transaction(“students”, “readwrite”); initialising transaction with dbstore name and giving it read/write permission

store = tx.objectStore(“students”); initialising store with store name

index = store.index(“s_name”); initialising index with the field name s_name

add generalised error handler that will alert you if you get any error while making a transaction

step 6: Inserting Data to DB

store.put({s_id: "s1", s_name: "Marry Fin", s_class: "5th year", s_age: 23});store.put({s_id: "s2", s_name: "Stive Altives", s_class: "2nd year", s_age: 23});store.put({s_id: "s3", s_name: "Bob Bozee", s_class: "4th year", s_age: 23});

this need to be added in onsuccess method after the initialisation of db, tx, store, and index

to add data to db .put() method is used store.put(), remember one this .put() method deals with 1 object/1data at a time

step 7: Retrieving Data

this need to be added in onsuccess method after the initialisation of db, tx, store, and index

// retriving data from DBlet data = store.get("s1"); //getting data by keydata.onsuccess = function () {console.log(data.result);}let data2 = index.get("Stive Altives"); //getting data by indexdata2.onsuccess = function () {console.log(data2.result.s_age);}

indexed DB works async so we need to wait for the response of the data

step 8: Close connection (main)

once you are done with transaction, don’t forget to close connection of the DB

tx.oncomplete = function () {db.close();}

FAQs

  • what is the max size of data we can store?

5000kb

  • browser support ?

--

--

Madhav Mansuriya
Madhav Mansuriya

No responses yet