Reputation: 343
Trying to use IndexedDB. I wrote a function that creates new Table and indexes and bring back callback.
But when I tried to use that function, it stop working - after onsuccess
state I got onblocked
state and onupgradeneeded
doesn't run...
How can I avoid blocking DB?
crtTable(db_name, table, indexes, callback) {
console.log("Initiate table creation");
let isSupport:boolean = this.checkDbSupport();
if(!isSupport) return;
let version;
let openRequest = indexedDB.open(db_name);
openRequest.onsuccess = (event) => {
console.log("Opening DB and find version");
version = (event.target as any).result.version;
//I GOT DB VERSION AND NOW I TRYING TO CLOSE IT!
(event.target as any).result.close();
version++;
console.log("reopen DB with new version")
let openRequest = indexedDB.open(db_name, version);
openRequest.onblocked = (event) => {
console.log("blocked");
}
openRequest.onupgradeneeded = (event) => {
console.log("update running")
let db = (event.target as any).result;
let transaction = db.createObjectStore(table[0], { keyPath: table[1] });
for(let index of indexes) {
transaction.createIndex(index[0], index[0], { unique: index[1] });
}
transaction.oncomplete = (event) => {
console.log("indexes setted");
}
callback("updated");
console.log("updated");
};
openRequest.onsuccess = (event) => {
openRequest.result.close();
callback("success");
console.log("success");
};
openRequest.onerror = (event) => {
openRequest.result.close();
callback("error");
console.log("error");
};
};
}
Upvotes: 3
Views: 2438
Reputation: 4150
You have to close other database connection before upgrading the database to new version.
The IDBOpenDBRequest.onblocked event handler is the event handler for the blocked event. This event is triggered when the upgradeneeded should be triggered because of a version change but the database is still in use (that is, not closed) somewhere, even after the versionchange event was sent.
https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onblocked
UPDATE:
You are trying to close it on onsuccess
and onerror
Event and which is not called as the database is already open and it calls onblocked
event try closing the db on onblocked
event too.
openRequest.onblocked = (event) => {
(event.target as any).result.close();
console.log("blocked");
}
Upvotes: 1