IndexedDB Manipulation with Dexie — CRUD Operations
--
IndexedDB is a way to store data in the browser.
It lets us store larger amounts of data than local storage in an asynchronous way.
Dexie makes working with IndexedDB easier.
In this article, we’ll take a look at how to start working with IndexedDB with Dexie.
Declare Database
We declare our IndexedDB database with the Dexie
class.
For example, we write:
(async () => {
var db = new Dexie("MyDatabase");
db.version(1).stores({
friends: "++id, name, age, *tags",
records: "id, score"
});
})()
friends
and records
are the tables.
The property strings are the columns that we want to index.
We shouldn’t declare all columns like in SQL.
The string has some special syntax. They include:
+
— Auto-incremented primary key&
— Unique*
— Multi-entry index[A+B]
— Compound index
Class Binding
We can map our entries to an instance of a class by writing:
class Friend {
save() {
return db.friends.put(this);
}get age() {
return moment(Date.now()).diff(this.birthDate, 'years');
}
}(async () => {
const db = new Dexie("MyDatabase");
await db.version(1).stores({
friends: "++id, name, age, *tags",
});
db.friends.mapToClass(Friend);
})()
We call mapToClass
to map our friends
entries to Friend
class instances.
Add Items
To add items into our database, we call the add
method.
For example, we can write:
(async () => {
const db = new Dexie("MyDatabase");
await db.version(1).stores({
friends: "++id, name, age, *tags",
});
await db.friends.add({
name: "joe",
age: 21
});
})()
to add an entry to the friends
table.
We can add multiple entries at once with the bulkAdd
method:
(async () => {
const db =…