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.
Getting started
We can get started by adding Dexie with a script tag:
<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
Then we can use it to create our data.
Then we can use it create a database, and write and read data from it.
To do this, we write:
const db = new Dexie("friend_database");
(async () => {
try {
await db.version(1).stores({
friends: 'name,age'
});
await db.friends.put({
name: "mary",
age: 28
})
const friend = await db.friends.get('mary');
console.log(friend.age);
} catch (error) {
console.log(error);
}
})()
We create the database with the Dexie
constructor.
Then we create a store in the database with:
await db.version(1).stores({
friends: 'name,age'
});
We add the friends
store into the database with the name
and age
fields indexed.
Indexed columns can be used to search for an entry.
Then we add the data with the put
method:
await db.friends.put({
name: "mary",
age: 28
})
Then we get an entry with the given indexed column with:
const friend = await db.friends.get('mary');
Then get the value of the age
field with:
console.log(friend.age);
Using Dexie as a Module
We can use Dexie withn the dexie
module.
To install it, we run:
npm i dexie
Then can write the same code with:
import Dexie from "dexie";
const db = new Dexie("friend_database");
(async () => {
try {
await db.version(1).stores({
friends: "name,age"
});
await db.friends.put({
name: "mary",
age: 28
});
const friend = await db.friends.get("mary");
console.log(friend.age);
} catch (error) {
console.log(error);
}
})();
The Dexie Class
The Dexie
class is both a class and a namespace.
The Dexie
instance represents a database connection.
It can also be used as an export area for functions, utilities, and classes.
If it’s used in the browser as a script tag, then only the window.Dexie
property is added.
If it’s used as a module, then it’s available as a default export.
The Table Class
The table represents an object-store.
We have direct access to instances of Table
for each object store that we’ve denied in our schema.
For example, if we have:
(async () => {
const db = new Dexie("FriendsAndPetsDB");
await db.version(1).stores({
friends: "++id,name,isCloseFriend",
pets: "++id,name,kind"
});
await db.open();
await db.friends.add({
name: "james",
isCloseFriend: true
});
await db.pets.add({
name: "mary",
kind: "dog",
fur: "long"
});
})()
Then we created the friends
and pets
store.
db.friends
and db.pets
are the table instances.
And we can manipulate data with them.
db.open
opens the database connection.
We called db.friends.add
to add data to the db.friends
store.
And we called db.pets.add
to add data to the db.pets
store.
Conclusion
We can manipulate IndexDB data easily with the Dexie library.