Monday, December 23, 2024

Dexie.js

 

What is Dexie.js?

Dexie.js is a lightweight, robust wrapper around IndexedDB, a browser-based database that allows developers to store large amounts of structured data directly in the user's browser. Dexie simplifies working with IndexedDB by providing a clean and developer-friendly API, including features like promises, queries, and transactions.


Why Do You Need Dexie.js?

  1. Simplifies IndexedDB:

    • IndexedDB has a complex and verbose API. Dexie abstracts that complexity and makes it easier to use.
  2. Asynchronous Programming:

    • Dexie uses promises and async/await for a modern, cleaner approach to handling asynchronous operations.
  3. Structured Storage:

    • Ideal for offline-first applications or features where client-side storage of large data sets is required (e.g., Progressive Web Apps (PWAs)).
  4. Transactions:

    • Provides support for atomic operations across multiple object stores.
  5. Observability:

    • Dexie offers advanced features like liveQuery for reactive programming, allowing real-time updates to your UI when data changes.
  6. Cross-Browser:

    • Dexie works across major browsers that support IndexedDB.

Key Features of Dexie.js

  1. Ease of Use: Simplifies defining a schema and querying data.
  2. Transactions: Supports multiple operations grouped into a single transaction.
  3. Reactive Queries: Use liveQuery to get real-time updates.
  4. Browser Compatibility: Works in modern browsers with IndexedDB support.

Basic Usage of Dexie.js

Installation

npm install dexie

Example: Setting Up a Database

import Dexie from 'dexie';

// Define your database
const db = new Dexie('MyDatabase');
db.version(1).stores({
  friends: '++id, name, age' // Auto-incrementing ID, indexed by name and age
});

// Add data
async function addFriend() {
  await db.friends.add({ name: 'John', age: 30 });
}

// Query data
async function getFriends() {
  const allFriends = await db.friends.toArray();
  console.log(allFriends);
}

// Run example
(async () => {
  await addFriend();
  await getFriends();
})();

Advanced Features

1. Using Transactions

Transactions ensure atomicity and consistency when performing multiple operations.

await db.transaction('rw', db.friends, async () => {
  await db.friends.add({ name: 'Alice', age: 25 });
  await db.friends.add({ name: 'Bob', age: 27 });
});

2. Reactive Queries with liveQuery

Automatically react to data changes:

import { liveQuery } from 'dexie';

const liveFriends = liveQuery(() => db.friends.toArray());

liveFriends.subscribe({
  next: (friends) => console.log('Updated friends list:', friends),
  error: (err) => console.error('Error:', err),
});

3. Filtering and Sorting

const youngFriends = await db.friends
  .where('age')
  .below(30)
  .toArray();
console.log(youngFriends);

4. Using Indices

You can define and query indices for efficient lookups.

const friendsNamedJohn = await db.friends.where('name').equals('John').toArray();
console.log(friendsNamedJohn);

Use Cases

  1. Offline-First Applications:

    • Store data locally in browsers for apps that need to function offline.
  2. Progressive Web Apps (PWAs):

    • Efficient client-side storage for offline availability.
  3. Real-Time Applications:

    • Use liveQuery to build applications that respond to data changes dynamically.
  4. Caching Large Data Sets:

    • Cache API responses or large datasets to reduce server load.
  5. Local User Preferences:

    • Store user preferences, settings, or temporary data for better UX.

Summary

  • Dexie.js makes it easy to use IndexedDB, which is essential for robust client-side storage in modern web apps.
  • It simplifies queries, transactions, and reactive programming.
  • Suitable for offline-first, real-time, or data-heavy applications.

 

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...