I have a very basic indexedDB with one key. I would like to retrieve this value to perform an operation. Unfortunately, the function that is supposed to do it returns undefined
before indexedDB could return the value.
Here are the functions:
const getValue = async () => {
const res = await IndexedDB.get(1)
return console.log("res", res) // displayed before "res" has finished
};
export default class IndexedDB {
static createDB() {
const request = indexedDB.open("myApp", 1);
request.onupgradeneeded = (e) => {
const db = e.target.result;
return db.createObjectStore("myData", { autoIncrement: true });
};
}
static addData(data) {
const db = indexedDB.open("myApp", 1);
db.onsuccess = (e) => {
const request = e.target.result
.transaction(["myData"], "readwrite")
.objectStore("myData")
.add(data);
request.onsuccess = (res) => res.target.result;
request.onerror = (err) => err
};
}
static get(key) {
const db = indexedDB.open("myApp", key);
db.onsuccess = (e) => {
const request = e.target.result
.transaction(["myData"])
.objectStore("myData")
.get(key);
request.onsuccess = (res) => res.target.result;
request.onerror = (err) => err
};
}
}
How to fix this?