Client-Side Storage in Javascript
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It allows web applications to store and retrieve objects in a database on the client's device. Unlike cookies, localStorage, and sessionStorage, IndexedDB offers more powerful storage capabilities and is designed to handle large amounts of data efficiently.
const request = window.indexedDB.open('myDatabase', 1); request.onerror = function(event) { console.error("Database error: " + event.target.errorCode); }; request.onsuccess = function(event) { const db = event.target.result; console.log("Database opened successfully"); };
This code opens (or creates, if it doesn't exist) a database named 'myDatabase' with version 1. It handles success and error events.
const transaction = db.transaction(['storeName'], 'readwrite'); const store = transaction.objectStore('storeName'); store.add({ id: 1, name: 'John Doe' });
This code adds an object to an object store named 'storeName' within the database.
const transaction = db.transaction(['storeName'], 'readonly'); const store = transaction.objectStore('storeName'); const request = store.get(1); request.onsuccess = function(event) { const data = event.target.result; console.log("Retrieved data:", data); };
This code retrieves an object from the object store with the key 1.
const transaction = db.transaction(['storeName'], 'readwrite'); const store = transaction.objectStore('storeName'); store.delete(1);
This code deletes the object with the key 1 from the object store.
IndexedDB offers various use cases in web applications:
While powerful, IndexedDB has some limitations:
IndexedDB provides a robust solution for client-side storage of structured data, offering capabilities beyond traditional storage mechanisms. However, it requires careful handling due to its asynchronous nature and complexity.