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
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();
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}`));
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}`));
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}`));
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}`));
Tips
- Use Transactions Wisely: When performing multiple operations, group them within a transaction to ensure consistency.
db.transaction('rw', db.friends, async () => {
// Multiple operations
});
Optimize for Performance:
Avoid reading or writing to the database excessively. Optimize queries and use indexes for faster retrieval.Error Handling:
Always handle errors to provide a better user experience and aid debugging during development.
Usage
Progressive Web Apps (PWAs):
Enable offline functionality by storing data locally for seamless user experiences.Caching:
Store static assets like images, styles, and scripts to reduce server requests and improve load times.Data-Intensive Applications:
Handle large datasets efficiently, such as in data visualization or analytics tools.Form Data Persistence:
Save user input locally to prevent data loss in case of accidental page reloads.
Top comments (1)
Playground: stackblitz.com/edit/web-platform-f...