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");
};
};
}
You have to close other database connection before upgrading the database to new version.
https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onblocked
UPDATE:
You are trying to close it on
onsuccessandonerrorEvent and which is not called as the database is already open and it callsonblockedevent try closing the db ononblockedevent too.