DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 90: Indexdb

What is IndexedDB?

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It provides a way for developers to create, read, navigate, and write to a user's local database. IndexedDB is especially useful for applications that require offline capabilities, allowing users to interact with data even when an internet connection is unavailable.

Setting Up with Dexie

To make our journey with IndexedDB smoother, we'll leverage Dexie, a minimalistic IndexedDB wrapper. Let's start by installing it:

npm install dexie
Enter fullscreen mode Exit fullscreen mode

Now, let's dive into the code:

// Import Dexie
import Dexie from 'dexie';

// Create a new database
const db = new Dexie('MyDatabase');

// Define a table
db.version(1).stores({
  friends: '++id,name,age',
});

// Open the database
db.open();
Enter fullscreen mode Exit fullscreen mode

This simple setup with Dexie creates a database named 'MyDatabase' with a table called 'friends,' each having an auto-incremented ID, name, and age.

Basic Operations

Add

const friend = { name: 'John Doe', age: 25 };

// Add a friend to the 'friends' table
db.friends.add(friend)
  .then(id => console.log(`Added friend with ID ${id}`))
  .catch(error => console.error(`Error adding friend: ${error}`));
Enter fullscreen mode Exit fullscreen mode

Query

// Retrieve all friends with age greater than 21
db.friends.where('age').above(21).toArray()
  .then(friends => console.log('Friends above 21:', friends))
  .catch(error => console.error(`Error querying friends: ${error}`));
Enter fullscreen mode Exit fullscreen mode

Update

// Update John Doe's age to 26
db.friends.where('name').equals('John Doe').modify({ age: 26 })
  .then(updated => console.log(`Updated ${updated} record(s)`))
  .catch(error => console.error(`Error updating friends: ${error}`));
Enter fullscreen mode Exit fullscreen mode

Delete

// Delete a friend by ID
const friendIdToDelete = 1;
db.friends.delete(friendIdToDelete)
  .then(() => console.log(`Deleted friend with ID ${friendIdToDelete}`))
  .catch(error => console.error(`Error deleting friend: ${error}`));
Enter fullscreen mode Exit fullscreen mode

Tips

  1. Use Transactions Wisely: When performing multiple operations, group them within a transaction to ensure consistency.
   db.transaction('rw', db.friends, async () => {
     // Multiple operations
   });
Enter fullscreen mode Exit fullscreen mode
  1. Optimize for Performance:
    Avoid reading or writing to the database excessively. Optimize queries and use indexes for faster retrieval.

  2. Error Handling:
    Always handle errors to provide a better user experience and aid debugging during development.

Usage

  1. Progressive Web Apps (PWAs):
    Enable offline functionality by storing data locally for seamless user experiences.

  2. Caching:
    Store static assets like images, styles, and scripts to reduce server requests and improve load times.

  3. Data-Intensive Applications:
    Handle large datasets efficiently, such as in data visualization or analytics tools.

  4. Form Data Persistence:
    Save user input locally to prevent data loss in case of accidental page reloads.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan