sbr
sbr

Reputation: 4823

indexedDb open onsucess without onupgradeneeded event

I am seeing that the indexedDb open request's on success callback is called even though the objectStoreNames list is empty.

I believe that the expected behavior is to have "onupgradeneeded" handler being called if objectStorenames.length is zero .

Does any one know why this could be happening ?

jsbin link

var db;
var DBOpenRequest = window.indexedDB.open("todos", 1);


DBOpenRequest.onerror = function(event) {
  console.error('error in open', event);
};

DBOpenRequest.onsuccess = function(event) {
  db = event.target.result;
  var objectStores =  db.objectStoreNames.length;
  console.log('success event, number of objectStores: ' +  objectStores);
};

DBOpenRequest.onupgradeneeded = function(event) {
  db = event.target.result;
  var objectStores =  db.objectStoreNames.length;

  console.log('upgradeneeded event, number of objectStores: ' +  objectStores);

  db.createObjectStore("toDoList", { keyPath: "taskTitle" }); 
};

Upvotes: 0

Views: 772

Answers (2)

sbr
sbr

Reputation: 4823

The issue was that there was another piece of code was calling indexedDB.open, but not listening to upgradeneeded event.

Upvotes: 0

nlawson
nlawson

Reputation: 11620

This seems to be the expected behavior of IndexedDB. You're looking up db.objectStoreNames.length inside of onupgradeneeded, before the object store has been created. You'll need to check it in the onsuccess callback instead.

I also note that the behavior in your jsbin is the same across Chrome, Firefox, Edge, and IE.

Upvotes: 1

Related Questions