recently, I intend to cache chat data locally. I encountered some problems in the process of using indexedDB,. The code is as follows
let db;
let chatDB = {
indexedDB: window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
//
openDB: function (dbname, version, store) {
let request = this.indexedDB.open(dbname, version || 1)
//
request.onupgradeneeded = function (event) {
//
db = event.target.result;
//........
};
//
request.onerror = function (e) {
console.log(e.currentTarget.error.message);
};
//
request.onsuccess = function (e) {
db = e.target.result;
};
},
//
addData: function (storeName, data) {
let store = db.transaction(storeName, "readwrite").objectStore(storeName)
let request = store.add(data);
request.onerror = function () {
console.error("add")
};
request.onsuccess = function () {
console.log("add")
};
}
}
chatDB.openDB(name,version);
chatDB.addData(db,name,data);
the error after execution is as follows
that is, db is only valid within onsuccess