Search code examples
javascriptindexeddbdexie

Querying in Dexie returns nothing when offset and limit are defined


Dexie noob here. I'm trying to use Dexie.js to get some data out of IndexedDB. I want to get the data in batches (think pagination) and it seems that only the first query is working.

Here's the data:

db.friends.bulkAdd([
  {name: "David", age: 42},
  {name: "Neil", age: 37},
  {name: "Freddie", age: 36},
  {name: "Elvis", age: 56},
  {name: "Calvin", age: 22},
]);

And here's query #1:

db.friends
.orderBy('age')
.limit(2)
.offset(0)
.toArray()
.then(function(result) {
  // Works as expected!
});

And query #2 which returns an empty []:

db.friends
.orderBy('age')
.limit(2)
.offset(2)
.toArray()
.then(function(result) {
  // result is []
}); 

If I leave limit(2) out from query #2 the query works as expected, but offset() and limit() together don't seem to work.

What am I doing wrong here? I'm probably just missing something very basic in how Dexie or IndexedDB works but can anyone help me out?

Here's a JSFiddle to test this.


Solution

  • Thanks for the jsfiddle. I can agree I found it strange at first when I read it. Then I realized the reason is the order of offset() and limit(). In your sample you are using limit() before offset(), which basically means:

    1. Limit the result to 2 items only.
    2. From that collection of 2 items, set an offset of 2, which leads to zero results.

    So the solution is to switch the order of limit and offset - use offset first and then apply a limit on that collection.