IndexedDB
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It uses indexes to enable high-performance searches of this data.
1. Key Concepts
Unlike localStorage which stores simple key-value strings synchronously, IndexedDB is:
- Transactional: All operations happen within a transaction.
- Asynchronous: Operations don't block the main thread.
- NoSQL: It stores JavaScript objects, not tables with rows/columns.
- Object-Oriented: Data is stored in "Object Stores".
2. Opening a Database
You open a database using indexedDB.open(). This request triggers events (success, error, upgradeneeded).
const request = indexedDB.open("MyDatabase", 1);
request.onerror = (event) => {
console.error("Database error:", event.target.errorCode);
};
request.onupgradeneeded = (event) => {
// This triggers if the client has no DB or a lower version.
// This is where you create object stores.
const db = event.target.result;
// Create an object store named "customers" with "ssn" as the key path
const objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name
objectStore.createIndex("name", "name", { unique: false });
};
request.onsuccess = (event) => {
const db = event.target.result;
console.log("Database opened successfully");
};
3. Adding Data
To add data, you start a transaction, get the object store, and call add().
function addCustomer(db) {
const transaction = db.transaction(["customers"], "readwrite");
const objectStore = transaction.objectStore("customers");
const customer = { ssn: "123-45-678", name: "John Doe", email: "john@example.com" };
const request = objectStore.add(customer);
request.onsuccess = () => {
console.log("Customer added to the store", request.result);
};
}
4. Retrieving Data
You can retrieve data by key or use an index.
function getCustomer(db, ssn) {
const transaction = db.transaction(["customers"]);
const objectStore = transaction.objectStore("customers");
const request = objectStore.get(ssn);
request.onsuccess = () => {
console.log("Customer:", request.result);
};
}
5. Promises Wrapper
The native API is event-based. Modern development often uses libraries like idb to wrap IndexedDB in Promises, allowing async/await.
programming/javascript/vanilla/javascript programming/javascript/vanilla/web-storage programming/javascript/vanilla/promises-async-await