Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

IndexedDB

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.

Examples

Opening a Database:

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.

Adding Data:

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.

Retrieving Data:

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.

Deleting Data:

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.

Use Cases

IndexedDB offers various use cases in web applications:

  • Offline Applications: Storing large amounts of data for offline access.
  • Complex Data Structures: Managing structured data such as user profiles, documents, or media files.
  • Caching: Storing frequently accessed data to improve performance.
  • File Storage: Storing files or blobs locally for applications like file management or offline document editing.

Limitations

While powerful, IndexedDB has some limitations:

  • Complexity: IndexedDB has a steeper learning curve compared to simpler storage mechanisms like localStorage or sessionStorage.
  • Asynchronous Operations: IndexedDB operations are asynchronous, which requires handling with callbacks or promises.
  • Browser Support: Support for IndexedDB may vary across browsers, and some older browsers may not fully support it.
  • Cross-Origin Restrictions: IndexedDB follows the same-origin policy, which restricts access to databases from different origins for security reasons.

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.