- How to Use IndexedDB -a NoSQL DB on the Browser
- Originally written by Viduni Wickramarachchi
- Translation from: The Gold Project
- This article is permalink: github.com/xitu/gold-m…
- Translator: zenblo
- Proofreader: PassionPenguin, Chorer
Use the NoSQL database IndexedDB on your browser
Have you ever heard of a NoSQL database on a browser?
IndexedDB is a large NoSQL storage system. It allows you to store arbitrary content in the user’s browser. In addition to the usual find, read, and update operations, IndexedDB supports transactions.
Source: developers. Google. Cn
You can find an example of IndexedDB below.
In this article, we will focus on the following:
- Why do we need IndexedDB
- How do I use IndexedDB in my application
- The function of with IndexedDB
- With IndexedDB limitations
- Whether IndexedDB is appropriate 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.
- Can store more than local storage (
localStorage
) much larger amount of data
IndexedDB has no special storage restrictions like localStorage (between 2.5MB and 10MB). The maximum limits of IndexedDB storage depend on the browser and disk space. For example, Chrome and Chromium-based browsers allow up to 80% of disk space to be used. If you have 100GB, IndexedDB can use up to 80GB of space, and a single source can use up to 60GB. Firefox allows up to 2GB per source, while Safari allows up to 1GB per source.
- You can store key-value based pairs
{ key: value }
Of any type
IndexedDB is more flexible for storing different data types. The supported data types include not only string types, but also binary data (ArrayBuffer objects, Blob objects, and so on). Internally, IndexedDB uses object storage to hold data.
- Provide a lookup interface
This feature is not available in other browser storage options, such as localStorage localStorage and sessionStorage sessionStorage.
- Useful for Web applications that do not require continuous networking
IndexedDB is useful for both online and offline working applications. For example, it can be used for client-side storage in a progressive Web application (PWA).
- You can store the application state
By storing application state for frequent users, you can greatly improve application performance, allowing the application to be subsequently synchronized with the back-end server and updated through lazy loading.
Let’s look at an IndexedDB structure that can store multiple databases.
With IndexedDB structure
How do I use IndexedDB in my application
In the following sections, we’ll explore how to use IndexedDB in your applications.
1. Usewindow.indexedDB
Open a database connection
const openingRequest = indexedDB.open('UserDB'.1);
Copy the code
In this case, UserDB is the database name and 1 is the version of the database. This returns an object that is an instance of the IDBOpenDBRequest interface.
2. Create object storage
When a database connection is enabled, an OnUpgradenneeded event is triggered which can be used to create object stores.
// Create the UserDetails object store and index
request.onupgradeneeded = (event) = > {
let db = event.target.result;
// Create the UserDetails object store
// Has an auto-incrementing ID
let store = db.createObjectStore('UserDetails', {
autoIncrement: true
});
// Create an index on the NIC attribute
let index = store.createIndex('nic'.'nic', {
unique: true
});
};
Copy the code
3. Insert data into the object store
Once the database connection is enabled, the data can be managed in the onSuccess event handler. Inserting data is done in four steps.
function insertUser(db, user) {
// Create a new transaction
const txn = db.transaction('User'.'readwrite');
// Get the UserDetails object store
const store = txn.objectStore('UserDetails');
// Insert new record
let query = store.put(user);
// Handle successful cases
query.onsuccess = function (event) {
console.log(event);
};
// Handle error cases
query.onerror = function (event) {
console.log(event.target.errorCode);
}
// Close the database after the transaction
txn.oncomplete = function () {
db.close();
};
}
Copy the code
After you create the insert function, you can insert more records using the requested onSuccess event handler.
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'
});
};
Copy the code
You can perform many operations on IndexedDB. These include:
- To read or find data from an object store by key
- To read or look up data from an object store by index
- Update recorded data
- Delete a record
- Migration from an older version of the database, etc
If you need information on how to do this, let me know in the comment section below. You can also see here for more information.
The function of with IndexedDB
IndexedDB provides many special features that other browser stores do not. Some of the features are briefly described below.
- Have asynchronous APIS
This allows expensive operations to be performed without blocking the UI thread and provides a better experience for the user.
- Support for reliable transactions
If one of these steps fails, the transaction is cancelled and the database is rolled back to its previous state.
- Support for version control
You can version control the database as it is created and update it as needed. It is also possible to migrate from an old version to a new version in IndexedDB.
- Private domain support
The database is a private domain, so no site can access another site’s IndexedDB storage. This is also known as the same origin policy.
With IndexedDB limitations
So far, IndexedDB seems promising for client-side storage. However, several limitations are worth noting.
- Although modern browsers support IndexedDB, browsers such as IE do not fully support it.
- IndexedDB is completely disabled in Firefox’s incognito browsing mode — when an application is accessed through an incognito window, the interface is unavailable and the application may fail.
Whether IndexedDB is appropriate for your application
Given the many features that IndexedDB offers, the answer to the million-dollar question is probably Yes! Before jumping to conclusions, however, ask yourself the following questions.
- Does your app need offline access?
- Do you need to store a large amount of data on the client?
- Need to quickly locate or find data in a large amount of data?
- Does the application use a browser supported by IndexedDB to access the client storage?
- Need to store various types of data, including JavaScript objects?
- Does writing or reading data from client storage need to be non-blocking?
If the answer to all of the above questions is yes, then IndexedDB is your best bet. However, if you don’t need such a feature, you can opt for localStorage, which provides an easy-to-use application programming interface (API) that most browsers adopt.
conclusion
When we consider all the client-side storage mechanisms, IndexedDB is the clear winner. Let’s take a look at a summary comparison of different client-side storage methods.
Hopefully you have a good idea of IndexedDB and its features. Let us know what you think, too.
If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.