DEV Community

Mritunjay Saha
Mritunjay Saha

Posted on

Using idb-keyval for indexedDB

Why use indexedDB instead of localStorage?

I came across indexedDB when I was looking for an alternate option for localStorage since it was not storing all the elements of an object. I needed to create react component using those values but since all the elements were not stored I was not able to display all the details on the client-side. So used indexedDB instead of localStorage to store the data.

What is indexedDB?

As per the MDN docs, indexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

It also says that IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database.

How to use indexedDB?

It might appear to be a bit difficult to use indexedDB but it becomes very simple when we use idb-keyval. Now, we can set and get data from the keyval store of the indexedDB using key-value pairs as we did in localStorage. Unlike localStorage, here we can stores arrays and objects too. We don't need to stringify the data before sending it on the keyval store of indexedDB. It is a promise-based keyval store

For using the idb-keyval, we need to install it using the following command:

npm install idb-keyval

And importing the set and get methods

import {set, get} from "idb-keyval"

Let see a simple use of indexedDB.

The syntax of the set method is

set("key", "value")

and the syntax of the get method is

get("key")

Alt Text

As you can see in the example that we have updated the value inside the then block. it is because idb-keyval is promise based and the get method will always return a promise.

Apart from the set and get methods there are other methods like del, clear, and key.

You can find the code in the Github Repository.

Top comments (0)