Skip to content Skip to sidebar Skip to footer

IndexedDB OpenCursor Transaction Onsuccess Returns Empty Array

req = db.openCursor(); req.customerData=new Array() //[{a:1}] req.onsuccess = function(e) { var cursor = e.currentTarget.result;

Solution 1:

A few things

  • I recommend not setting custom properties of an IDBRequest object. Create and access objects that are in an outer scope instead.
  • There is no need to use event.currentTarget. event.target is sufficient (and so is 'this', and so is the request object itself).
  • onversionchange is deprecated.
  • Due to the asynchronous nature of indexedDB, you may be trying to print something out to the console that does not yet exist, or no longer exists. Instead, try printing something out when the transaction completes.

For example:

function populateArray(openDatabaseHandle, onCompleteCallbackFunction) {
  var transaction = openDatabaseHandle.transaction('store');
  var store = transaction.objectStore('store');
  var myArray = [];
  var request = store.openCursor();
  request.onsuccess = function() {
    var cursor = this.result;
    if(!cursor) return;
    myArray.push(cursor.value);
    cursor.continue();
  };
  transaction.oncomplete = function() {
    onCompleteCallbackFunction(myArray);
  };
}

// An example of calling the above function
var conn = indexedDB.open(...);
conn.onsuccess = function() {
  populateArray(this.result, onPopulated);
};

// An example of a callback function that can be passed to 
// the populateArray function above
function onPopulated(data) {
  console.debug(data);
  data.forEach(function(obj) {
    console.debug('Object: %o', obj);
  });
}

Post a Comment for "IndexedDB OpenCursor Transaction Onsuccess Returns Empty Array"