Taming IndexedDB [2/3]

Dani Vijay
Mar 6, 2018 · 2 min read

In last session, we setup a database and created an object store within. If you feel this strange, feel free to read Taming IndexedDB — Part 1. Else, lets get moving!

Working with Data

Read, write and delete operations can be performed using get, put and delete respectively. Makes sense, right?

As I mentioned before, get is used to read data from object stores. It should be used within a transaction. As this is for just reading data, a readonly transactions makes sense.

dbPromise.then(function(db) {
var tx = db.transaction('store', 'readonly');
var store = tx.objectStore('store');
return store.get('sandwich');
}).then(function(val) {
console.dir(val);
});

The code above returns data with primary key ‘sandwich’. What if we want to fetch everything out of an object store? getAll is here to rescue!

dbPromise.then(function(db) {
var tx = db.transaction('store', 'readonly');
var store = tx.objectStore('store');
return store.getAll();
}).then(function(items) {
console.log('Items by name:', items);
});

Updates and deletions can be performed in the same manner, but with put and delete, of course!!

// update using put

It’s not over, yet!

Using the above operations are pretty much straight forward. But we forgot to address the elephant in the room, Cursor. Remember what we learned before.

Cursor is used to iterate through multiple records in database.
- Taming IndexedDB — Part 1

It selects each object in an object store or index one by one, letting you do something with the data as it is selected. It should be wrapped within transactions, like other operations.

openCursor is used to initiate the cursor, which can accept an optional key range as argument. cursor.continue is used for iterate through objects, until no object remaining, which returns undefined.

dbPromise.then(function(db) {
var tx = db.transaction('store', 'readonly');
var store = tx.objectStore('store');
return store.openCursor();
}).then(function logItems(cursor) {
if (!cursor) {
return;
}
console.log('Cursored at:', cursor.key);
for (var field in cursor.value) {
console.log(cursor.value[field]);
}
return cursor.continue().then(logItems);
}).then(function() {
console.log('Done cursoring');
});

We’re really close to wrap up, but some more things you should master to become the Ultimate IndexedDB Ninja!

Sea ya!

Update: Taming IndexedDB [3/3]

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in…

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in the field of Mobile Web Development.

Dani Vijay

Written by

Full Stack Web Dev | Tech Evangelist | https://twitter.com/UtmostDev | https://github.com/danivijay/ | https://linkedin.com/in/danivijay

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in the field of Mobile Web Development.