What is IndexedDB?
What is IndexedDB and how does it work?
IndexedDB is an advanced browser storage and data manipulation method that allows storing large amounts of structured data as objects with indexed access. Unlike LocalStorage or SessionStorage, IndexedDB supports complex queries, data structures, and large-scale data storage.
IndexedDB is particularly useful when working with large datasets or complex objects that don't fit in conventional storage methods.
IndexedDB operates by creating databases, then adding, retrieving or deleting data using indexes that facilitate efficient data queries. It enables working with large numbers of objects while ensuring fast queries and interactions.
// Opening IndexedDB
const request = indexedDB.open('myDatabase', 1);
request.onsuccess = function(event) {
const db = event.target.result;
// Adding data
const transaction = db.transaction('store', 'readwrite');
const store = transaction.objectStore('store');
store.add({ id: 1, name: 'John' });
transaction.oncomplete = function() {
console.log('Data added successfully');
};
};
// Querying data
const request = indexedDB.open('myDatabase', 1);
request.onsuccess = function(event) {
const db = event.target.result;
const transaction = db.transaction('store', 'readonly');
const store = transaction.objectStore('store');
const getRequest = store.get(1);
getRequest.onsuccess = function(event) {
console.log(getRequest.result);
};
};
IndexedDB uses databases, object stores, and transactions. For example, we can create one or more stores to organize our data.
Advantages:
Disadvantages:
IndexedDB is often used when working with large datasets or complex objects that don't fit other storage methods. Example use cases include:
IndexedDB is a powerful and versatile storage method that enables storing large, complex data in browsers. It provides significantly more capabilities including database management and data querying tools. It's most valuable when working with large or complex datasets. Currently, IndexedDB is useful in many scenarios, particularly for applications that work online/offline or require interactive data processing.