My script runs into the error:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
The script should check, if the database is filled. If not fill the database with initial values. After that display the values in inputfields.
The error occures at var data = marmaInfo.result
var indexedDB = window.indexedDB
var db;
// Open (or create) the database
var open = indexedDB.open("marmaDB", 1);
console.log("open Db ...");
// Create the schema
console.log("creating schema ...");
open.onupgradeneeded = function() {
db = open.result;
var store = db.createObjectStore("marmasStore", {keyPath: "id"});
store.createIndex('sanskrit', 'sanskrit', { unique: false });
};
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
open.onsuccess = function() {
console.log("open DB DONE");
// Start a new transaction
db = open.result;
store = getObjectStore("marmasStore", 'readwrite');
//var tx = db.transaction("marmasStore", "readwrite");
//var store = tx.objectStore("marmasStore");
//var index = store.index("NameIndex");
// Initial data
const initialMarmaData = [
{ id: "ani_ll", sanskrit: "ani"},
];
// Store values
// initial DB filling
var key = $('#marmaID').val();
console.log("key " + key );
var marmaInfo = store.get(key);
//marmaInfo.onsuccess = function(evt) {
var data = marmaInfo.result //###### ERROR at this line ######
if (data.sanskrit == 0){
console.log("record " + key + ":", record);
console.log("initial filling DB ...");
var store = getObjectStore("marmasStore", 'readwrite');
initialMarmaData.forEach((marma) => {
var request = store.put(marma);
request.onsuccess = (event) => {
console.log(event.target.result + " initial filling DB DONE");
};
});
}
//}
//fill the form with DB values
console.log("filling form ...");
document.getElementById('sanskrit').value = data.sanskrit;
console.log("filling form DONE");
}
2
Answers
Here, if
onsuccess
is called beforeonupgradeneeded
, your variablestore
has not been instantiated even if you give it a value. Maybe is it a problem in your case.However you should try to use
let
andconst
if possible, for better variable’s scope usageIt looks like you need to wait for the result of
getKey
to return. This code was taken from mdn web docs:The
.onsuccess
call essentially waits for thegetKey
function to return, therefor defining the result.