Monday, December 23, 2024

What is IndexedDB?

 

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?

  1. Persistent Storage:

    • Data stored in IndexedDB persists across browser sessions unless explicitly deleted.
  2. Large Storage:

    • IndexedDB allows storing significantly larger data compared to localStorage or sessionStorage.
  3. Structured Data:

    • Supports complex data types, including objects and arrays.
  4. Offline Support:

    • Ideal for offline-first applications, where data is stored locally and synced with a server when online.
  5. Asynchronous:

    • IndexedDB operations are non-blocking, meaning they do not freeze the main thread.

Key Features of IndexedDB

  1. Transactional:

    • Operations are grouped into transactions for atomicity and consistency.
  2. Key-Value Store:

    • Data is stored as key-value pairs, where keys are used to access records.
  3. Indexes:

    • Create indexes for efficient querying.
  4. Event-Driven:

    • Operations are event-based and use callbacks or promises.
  5. Cross-Origin Storage:

    • Data stored in IndexedDB is scoped to the origin (protocol + domain + port).

Basic Concepts

  1. Database:

    • The top-level container. Multiple databases can exist per application.
  2. Object Store:

    • Similar to tables in relational databases, where data is stored.
  3. Key:

    • Unique identifier for a value in an object store.
  4. Transaction:

    • A single unit of work involving one or more object stores.
  5. Index:

    • A secondary representation of data for fast lookups.

IndexedDB Workflow

  1. Open or create a database.
  2. Create object stores and indexes (done during the onupgradeneeded event).
  3. 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

  1. Offline-First Applications:

    • Store data locally to enable app functionality without an internet connection.
  2. Progressive Web Apps (PWAs):

    • Cache data for fast, offline-capable experiences.
  3. Large Data Storage:

    • Store datasets too large for localStorage or sessionStorage.
  4. Complex Queries:

    • Use indexes for efficient lookups and querying of structured data.
  5. Gaming Applications:

    • Save progress, settings, or in-game assets locally.

Limitations

  1. Complex API:

    • Native IndexedDB is verbose and challenging to work with (tools like Dexie.js simplify this).
  2. Browser Compatibility:

    • Supported in modern browsers but may not work in some legacy environments.
  3. 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

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...