Reputation: 4823
I am seeing that sometimes neither of the events are being fired when doing indexedDb.open()
.
If I set a timeout and observe the state of openRequest
, the ready state is set = 'done'. If I do any transaction on the db in the openRequest.result
, it works fine.
My guess is that in some cases the openRequest
execution is complete before we get to attach onsuccess
or other event handlers, in other words it does not get executed in the next event loop.
So, I can inspect the state after an 'x' amount of time if no event is fired. However this approach is hackish and fragile. Does anyone know of a better way to address this?
var db;
var openRequest = window.indexedDB.open("todos", 1);
openRequest.onerror = function(event) {
console.error('error in open', event);
};
openRequest.onsuccess = (event) => {
console.log('success ' , event)
};
openRequest.onupgradeneeded = (event) => {
console.log('upgradeneeded ' , event);
db = event.target.result;
db.createObjectStore("toDoList", { keyPath: "taskTitle" });
};
openRequest.onblocked = (event) => {
console.log('blocked ' , event);
};
setTimeout( () => {
console.log('timeout');
console.log(openRequest.readyState) // equals done
}, 10000)
Upvotes: 1
Views: 443
Reputation: 8337
Either a "success"
or an "error"
event must fire when readyState
becomes "done"
. If that's not happening then you've found a browser bug.
As noted in a comment, you'll want db = event.target.result
in the onsuccess
handler as well, otherwise db
will not be set if an upgrade was not necessary. Are you certain that this isn't the source of your error? (i.e. maybe success
was firing, you just weren't capturing the result?)
in some cases the openRequest execution is complete before we get to attach 'onsuccess' or other event handlers
If that happened it would be a browser bug. Are you seeing consistent behavior across browsers? Can you reliable reproduce this?
Upvotes: 1