Introduction to IndexedDB

Spread the love

Relational Databases like MySQL are great for storing , updating and reading data. Though they come with two disadvantages. 

  • Since the databases reside on the server, fetching and updating data depends on the quality of the user’s internet connection. If the user has slow internet, it will take much longer to data to be fetched and updated.
  • Also when the user loses connectivity, there is no way to connect to the database until the connection is restored

IndexedDB is a JavaScript-based object-oriented database which runs client-side on your browser, so it works in bad networks or when the user is offline. IndexedDB stores data as key value pairs, key can be any string, value can be any object. IndexedDB also indexes  data stored so that you can perform high performance searches on the data. IndexedDB also supports transactions

IndexedDB is supported on the current version of most browsers, you can find out which versions of browsers support indexedDB by visiting this link.

Terminology 

Some of the common terminology with indexedDb is 

Database

This is the highest level. It contains zero or more object stores, which contain the data you would like to persist. You can create multiple databases.

Object Store

It is an individual bucket to store data like tables in relational databases. Normally you create one object store for each type of data, like an object store for Users, another for Products, etc.

Index

Its a kind of object store for organizing data in another object store, you can think of it as properties of an object like employee_id for a employee.

Operation

  A task which modifies the database. There are 4 types of operations , referred to as CRUD.

Create – or insert data into a database

Read – read data from the database

Update – update existing data on the database

Delete – delete data from the database.

Transaction

A transaction is an operation, or group of operations, that ensures database integrity. If one of the actions within a transaction fail, none of them are applied and the database returns to the state it was in before the transaction began. All read or write operations in IndexedDB must be part of a transaction. This allows for atomic read-modify-write operations without worrying about other threads acting on the database at the same time.

Simplified IndexedDB

To make working with indexedDb easier, you can use one of the many opensource libraries like https://github.com/jakearchibald/idb which allows you to use promises with indexedDb.

The API section of the README gives a good overview on how to perform various operations.

There are also other libraries that provide higher level APIs which are easier to use than indexedDB lik localForage and Dexie.js which lets you start using indexedDb quickly and easily.