Reputation: 4342
I am working with IndexedDB
and I have a database with about 4000 records. I am trying to load small chucks of records at a time. Something similar to the infinite scrolling you see on your twitter feed. I've tried to Google this and found no code examples, but came across the advance method. I tried to use that, but still no success. The browser loaded all the records at once. How do I make it so I am only loading small amounts of records at a time?
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
res.advance(25);
res.continue();
console.log(res.value);
}
}
}
Upvotes: 0
Views: 707
Reputation: 14499
The res.advance(25) will skip 25 rows but it will still load the rest. I changed your code + added some comments. You might want to use something like this:
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
var results = null; // variable to store the results
var startIndex = 25,
maxResults = 25;
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
if (!results) {
results = [];
// skip rows, but only the first time
res.advance(startIndex);
} else {
results.push(res.value)
// We don't have 25 results yet, continue to load a next one
if(results.length < maxResults) {
res.continue();
}
}
}
}
transaction.oncomplete = function() {
// maxResults loaded or maybe it was the last page so it might not be full
console.log(results);
}
}
The below example is a lot more simple and works with autoincrement, but the pages are only full when results aren't deleted (not full code, but it's all about the IDBKeyRange.bound(0, 25))
var cursor = objectStore.openCursor(IDBKeyRange.bound(0, 25));
var results = [];
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
results.push(res.value)
}
}
transaction.oncomplete = function() {
console.log(results);
}
Upvotes: 1