NewUser
NewUser

Reputation: 3819

How to get all values from indexeddb

I am working on storing some data in the indexedDb.

I have created a method which saves the data into the indexedDb. I have stored exactly 49 records. I am trying to retrieve all of them. I have written the below code for getting the values. No other code except this line exist in my js file.

function crap() {
var indexedDb = window.indexedDB || window.webkitIndexedDB || window.msIndexedDB;

var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

var openedDb = indexedDb && indexedDb.open;

var isIndexDbTransactionPossible = window.IDBTransaction || window.webkitIDBTransaction;
if (isIndexDbTransactionPossible) {
    isIndexDbTransactionPossible.READ_WRITE = isIndexDbTransactionPossible.READ_WRITE || 'readwrite';
    isIndexDbTransactionPossible.READ_ONLY = isIndexDbTransactionPossible.READ_ONLY || 'readonly';
}

var request = indexedDb.open('Offline', DB_VERSION);

request.onupgradeneeded = function(e) {
    var db = e.target.result;

    if (db.objectStoreNames.contains('tab')) {
        db.deleteObjectStore('tab');
    }

    var store = db.createObjectStore('tab', {keyPath: 'id', autoIncrement: true});
};

request.onsuccess = function(e) {
    console.log("DB opened");
    var db = e.target.result;

    var store= db.transaction('tab', IDBTransaction.READ_ONLY).objectStore('tab');

    var cursor = store.openCursor();

    cursor.onsuccess = function(event) {

        var c = event.target.result;

        if (c) {
            console.log("New value")
            c.continue();
        }
    };
};
}

I am seeing "New Value" printed 124 times. I am not sure why the cursor.continue() is not returning null after 49th attempt. Any help is much appreciated.

I am positive that this method is not called more than one time. "DB opened" is logged only one.

Upvotes: 5

Views: 16413

Answers (2)

Henrik Carlström
Henrik Carlström

Reputation: 153

Just use the getAll function:

    var allRecords = store.getAll();
    allRecords.onsuccess = function() {
        console.log(allRecords.result);
    };

Read more in the documentation: Working with IndexedDB

Upvotes: 11

Josh
Josh

Reputation: 18690

Instead of checking readyState, just check for whether the cursor is defined in your cursor request callback. Here is an example. I modified the names of your variables slightly for clarity.

cursorRequest.onsuccess = function(event) {
  var cursor = event.target.result;

  if(cursor) {
    var value = cursor.value;
    console.log('New value:', value);
    cursor.continue();
  } else {
    // Undefined cursor. This means either no objects found, 
    // or no next object found
    // Do not call cursor.continue(); in this else branch because 
    // there are no more objects over which to iterate.  
    // Coincidentally, this also means we are done iterating.
    console.log('Finished iterating');
  }
}

Upvotes: 3

Related Questions