In depth study of indexeddb API and its usage in practice.
Have you ever heard of NoSQL database on browser?
Indexeddb is a large NoSQL storage system. It allows you to store almost anything in the user’s browser. In addition to the usual search, get and place operations, indexeddb also supports transactions.
You can find an example of indexeddb below.
In this article, we will focus on the following.
- Why do we need indexeddb?
- How do we use indexeddb in our applications?
- Functions of indexeddb
- Limitations of indexeddb
- Is indexeddb suitable for your application?
Why do we need indexeddb?
Indexeddb is considered more powerful than localstorage!
Do you know the reason behind it? Let’s find out.
You can store a much larger amount of data than localstorage
There’s nothing like thatlocalStorage
Such a special limit (between 2.5Mb and 10MB). The maximum limit depends on the browser and disk space. For example, browsers based on chrome and chromium allow up to 80% of disk space. If you have 100GB, indexeddb can use up to 80GB of space, and a single origin can use up to 60GB. Firefox allows up to 2GB per origin, while Safari allows up to 1GB per source.
You can store any type of value based on {key: value} pairs
More flexibility to store different data types. This means not only string, but also binary data (arraybuffer object, blob object, etc.). It uses object storage to hold data internally.
Provide search interface
This stores options in other browsers (for examplelocalStorage
andsessionStorage
)Not available in.
Useful for web applications that do not require a continuous Internet connection
Indexeddb is very useful for both online and offline applications. For example, it can be used for client storage in progressive Web Applications (PWA).
Application status can be stored
By storing application state for frequently used users, application performance can be greatly improved. Later, the application can synchronize with the back-end server and update the application by delaying loading.
Let’s look at the structure of indexeddb, which can store multiple databases.
The structure of indexeddb
How do we use indexeddb in our applications?
In the following sections, we’ll look at how to use indexeddb to boot the application.
1. Use“ window.indexedDB ”Open database connection
const openingRequest = indexedDB.open('UserDB', 1);
ad locumUserDB
Is the database name,1
Is the version of the database. This returns an object that isIDBOpenDBRequest
Interface.
2. Create object storage
When a database connection is opened, theonupgradeneeded
Event that can be used to create an object store.
//Create the userdetails object repository and index
request.onupgradeneeded = (event) => {
let db = event.target.result;
//Creating a userdetails object store
//With auto increment ID
let store = db.createObjectStore('UserDetails', {
autoIncrement: true
});
//Creating an index on NIC properties
let index = store.createIndex('nic', 'nic', {
unique: true
});
};
3. Insert data into object storage
Once you open the connection to the database, you canonsuccess
Manage data in the event handler. Inserting data takes place in four steps.
function insertUser(db, user) {
//Create a new thing
const txn = db.transaction('User', 'readwrite');
//Get the userdetails object store
const store = txn.objectStore('UserDetails');
//Insert new record
let query = store.put(user);
//Handling successful use cases
query.onsuccess = function (event) {
console.log(event);
};
//Handling failure cases
query.onerror = function (event) {
console.log(event.target.errorCode);
}
//Close the database when the transaction is complete
txn.oncomplete = function () {
db.close();
};
}
Once the insert function is created, the requestedonsuccess
Event handlers can be used to insert more records.
request.onsuccess = (event) => {
const db = event.target.result;
insertUser(db, {
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
});
insertUser(db, {
email: '[email protected]',
firstName: 'Ann',
lastName: 'Doe'
});
};
Many operations can be performed on indexeddb, some of which are as follows:
- Read / search data from object storage through key
- Press index to read / search data from the object store
- Update record data
- Delete record
- Migrate from a previous version of the database, etc
Functions of indexeddb
Indexeddb provides many special functions, which can’t be realized by other browser storage. Some functions are briefly described below.
With asynchronous API
This allows expensive operations to be performed without blocking UI threads and provides a better user experience.
Support transactions to ensure reliability
If a step fails, the transaction is cancelled and the database is rolled back to its previous state.
Support version control
You can version the database when you create it and upgrade it when you need it. You can also migrate from the old version to the new version in indexeddb.
Private domain
The database is a domain private database, so no other website can access the indexeddb storage of other websites. That’s what it’s calledHomologous strategy。
Limitations of indexeddb
So far, indexeddb seems promising for client-side storage. However, there are some notable limitations.
- Even with the support of modern browsers, ie and other browsers are not fully supported.
- Indexeddb is completely disabled in private browsing mode by Firefox – this may cause your application to fail when accessing through stealth windows.
Is indexeddb suitable for your application?
Based on many functions provided by indexeddb, the answer to this million dollar question may be yes! However, before drawing a conclusion, ask yourself the following questions.
- Do you need offline access to your app?
- Do you need to store a lot of data on the client?
- Do you need to quickly find / search data in a large amount of data?
- Does your application use indexeddb supported browser to access client storage?
- Do you need to store all kinds of data, including JavaScript objects?
- Is non blocking required for write / read from client storage?
If the answer to all the above questions is “yes”, indexeddb is your best choice. But if you don’t need such a feature, you might as well choose something likelocalStorage
Such a storage method, because it provides a wide range of browser applications, and has an easy to use API.
summary
When we consider all the client storage mechanisms, indexeddb is a clear winner. Let’s take a look at the summary and comparison of different client storage methods.
Cookies | Web Storage | IndexedDB | |
---|---|---|---|
storage | Small query table with key value and data value pair | Only characters Serial key and value storage |
Object storage, can store any type of data, including objects |
capacity | 4KB | 5MB-25MB | Above 50MB |
Indexes | I won’t support it | I won’t support it | support |
API call type | synchronization | synchronization | asynchronous |
Operational performance | Direct execution | Direct execution | affair |
learning curve | low | low | high |
I hope you have a clear understanding of indexeddb and its benefits.