What is IndexedDB?
IndexedDB is a low-level API provided by modern browsers for storing large amounts of structured data in a user's browser. It enables developers to build powerful client-side applications by offering a transactional, key-value database system.
Why Use IndexedDB?
-
Persistent Storage:
- Data stored in IndexedDB persists across browser sessions unless explicitly deleted.
-
Large Storage:
- IndexedDB allows storing significantly larger data compared to
localStorageorsessionStorage.
- IndexedDB allows storing significantly larger data compared to
-
Structured Data:
- Supports complex data types, including objects and arrays.
-
Offline Support:
- Ideal for offline-first applications, where data is stored locally and synced with a server when online.
-
Asynchronous:
- IndexedDB operations are non-blocking, meaning they do not freeze the main thread.
Key Features of IndexedDB
-
Transactional:
- Operations are grouped into transactions for atomicity and consistency.
-
Key-Value Store:
- Data is stored as key-value pairs, where keys are used to access records.
-
Indexes:
- Create indexes for efficient querying.
-
Event-Driven:
- Operations are event-based and use callbacks or promises.
-
Cross-Origin Storage:
- Data stored in IndexedDB is scoped to the origin (protocol + domain + port).
Basic Concepts
-
Database:
- The top-level container. Multiple databases can exist per application.
-
Object Store:
- Similar to tables in relational databases, where data is stored.
-
Key:
- Unique identifier for a value in an object store.
-
Transaction:
- A single unit of work involving one or more object stores.
-
Index:
- A secondary representation of data for fast lookups.
IndexedDB Workflow
- Open or create a database.
- Create object stores and indexes (done during the
onupgradeneededevent). - Perform transactions (read, write, or delete data).
How to Use IndexedDB
Example 1: Setting Up a Database
const request = indexedDB.open('MyDatabase', 1);
request.onupgradeneeded = function (event) {
const db = event.target.result;
// Create an object store with a keyPath
const objectStore = db.createObjectStore('customers', { keyPath: 'id' });
// Create an index for efficient lookups
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
};
request.onsuccess = function (event) {
const db = event.target.result;
console.log('Database opened successfully');
};
request.onerror = function (event) {
console.error('Database error:', event.target.errorCode);
};
Example 2: Adding Data
const request = indexedDB.open('MyDatabase', 1);
request.onsuccess = function (event) {
const db = event.target.result;
const transaction = db.transaction('customers', 'readwrite');
const objectStore = transaction.objectStore('customers');
const customer = { id: 1, name: 'John Doe', email: 'john@example.com' };
const addRequest = objectStore.add(customer);
addRequest.onsuccess = function () {
console.log('Customer added successfully');
};
transaction.oncomplete = function () {
console.log('Transaction completed');
};
};
Example 3: Reading Data
const request = indexedDB.open('MyDatabase', 1);
request.onsuccess = function (event) {
const db = event.target.result;
const transaction = db.transaction('customers', 'readonly');
const objectStore = transaction.objectStore('customers');
const getRequest = objectStore.get(1);
getRequest.onsuccess = function () {
console.log('Customer:', getRequest.result);
};
};
Example 4: Using Indexes
const request = indexedDB.open('MyDatabase', 1);
request.onsuccess = function (event) {
const db = event.target.result;
const transaction = db.transaction('customers', 'readonly');
const objectStore = transaction.objectStore('customers');
const index = objectStore.index('name');
const getRequest = index.get('John Doe');
getRequest.onsuccess = function () {
console.log('Customer found:', getRequest.result);
};
};
When to Use IndexedDB
-
Offline-First Applications:
- Store data locally to enable app functionality without an internet connection.
-
Progressive Web Apps (PWAs):
- Cache data for fast, offline-capable experiences.
-
Large Data Storage:
- Store datasets too large for
localStorageorsessionStorage.
- Store datasets too large for
-
Complex Queries:
- Use indexes for efficient lookups and querying of structured data.
-
Gaming Applications:
- Save progress, settings, or in-game assets locally.
Limitations
-
Complex API:
- Native IndexedDB is verbose and challenging to work with (tools like Dexie.js simplify this).
-
Browser Compatibility:
- Supported in modern browsers but may not work in some legacy environments.
-
Quota Limits:
- Storage space is limited by the browser and can vary between devices.
Summary
- IndexedDB is a powerful browser-based database for storing structured data.
- Suitable for offline-first and data-heavy applications.
- Dexie.js or similar libraries can simplify working with IndexedDB.
No comments:
Post a Comment