Introduction to Dexie.js
Dexie.js is a minimalistic yet powerful IndexedDB wrapper that simplifies database operations in web applications. It provides a straightforward API for managing databases and offers numerous features to ease the development process. In this article, we will explore Dexie’s capabilities, explore its APIs with code snippets, and create a sample application using Dexie.js.
Getting Started with Dexie.js
First, include Dexie.js in your project. You can use a CDN, npm, or yarn to do this.
// Using CDN <script src="https://unpkg.com/dexie/dist/dexie.js"></script> // Using npm npm install dexie // Using yarn yarn add dexie
Setting Up Dexie
Initialize Dexie and define your database schema.
const db = new Dexie('MyDatabase'); db.version(1).stores({ friends: '++id, name, age' });
Basic API Operations
Adding Data
Use the add()
method to insert data into the database.
db.friends.add({name: 'John Doe', age: 25}).then(() => { console.log('Friend added'); }).catch((error) => { console.error('Error adding friend: ', error); });
Retrieving Data
Use the get()
method to retrieve data by primary key, or where()
to query.
db.friends.get(1).then((friend) => { console.log('Retrieved friend: ', friend); }); db.friends.where('age').below(30).toArray().then((youngFriends) => { console.log('Friends below 30: ', youngFriends); });
Updating Data
Use the update()
method to modify existing data.
db.friends.update(1, {age: 26}).then((updated) => { if (updated) { console.log('Friend updated'); } else { console.log('Friend not found'); } });
Deleting Data
Use the delete()
method to remove data from the database.
db.friends.delete(1).then(() => { console.log('Friend deleted'); });
Using Transactions
Utilize transactions for batch operations.
db.transaction('rw', db.friends, () => { db.friends.add({name: 'Jane Doe', age: 30}); db.friends.add({name: 'Sam Smith', age: 27}); }).then(() => { console.log('Transaction committed'); }).catch((error) => { console.error('Transaction failed: ', error); });
Advanced Queries
Dexie.js offers advanced query capabilities such as compound queries and multi-field sorting.
db.friends.where('[age+name]').between([20, 'A'], [30, 'Z']).toArray().then((results) => { console.log('Advanced query results: ', results); });
Sample Application Using Dexie.js
Let’s create a simple application to manage a list of tasks.
Define Database Schema
const db = new Dexie('TaskApp'); db.version(1).stores({ tasks: '++id, title, completed' });
Add Task Function
function addTask(title) { db.tasks.add({title, completed: false}).then(() => { console.log('Task added'); }); } addTask('Learn Dexie.js');
Get Tasks Function
function getTasks() { db.tasks.toArray().then((tasks) => { console.log('Tasks: ', tasks); }); } getTasks();
Update Task Function
function completeTask(id) { db.tasks.update(id, {completed: true}).then(() => { console.log('Task completed'); }); } completeTask(1);
Delete Task Function
function deleteTask(id) { db.tasks.delete(id).then(() => { console.log('Task deleted'); }); } deleteTask(1);
With these basic operations, you can build a robust task management application using Dexie.js.
Hash: e41ab908706209af42383ed09c3d4a409249f06d66a36115c0ade2691e2613f3