indexeddb get data from index n to index k

Viewed 393

how to get data from an object Store from index number n to k. For example if we have 100 records in an store (ProductStore), an I need to get from index 11 to 20 or 50 to 60. I need to use this in pagination. In mysql we can use LIMIT and OFFSET clouse,is there any equivalent to OFFSET in Indexeddb.

1 Answers

You can use cursor.advance to skip past some records. There is no limit with cursors, you simply stop iterating by counting how many times you iterated.

Something like this:

function query(db, criteria, offset, limit) {
  return new Promise((resolve, reject) => {
    const results = [];
    const transaction = db.transaction('store');
    transaction.oncomplete = event => resolve(results);
    transaction.onerror = event => reject(event.target);
    const store = transaction.objectStore('store');
    const index = store.index('index');
    const request = index.openCursor(criteria);

    let advanced = offset === 0;
    let counter = 0;
    
    request.onsuccess = event => {
      const cursor = event.target.result;
      if (!cursor) {
        return;
      }

      if (!advanced) {
        advanced = true;
        cursor.advance(offset);
      }

      counter++;
      results.push(cursor.value);

      if (counter >= limit) {
        return;
      }
      cursor.continue();
    };
  });
}
Related