Using the IndexedDB API we have these 2 methods: getAll()
and getAllKeys()
with an usage example below:
let transaction = this.db.transaction(["table"]);
let object_store = transaction.objectStore("table");
request = object_store.getAll(); /* or getAllKeys() */
request.onerror = (event) => {
console.err("error fetching data");
};
request.onsuccess = (event) => {
console.log(request.result);
};
The problem is getAll()
seems to retrieve only the data in an array format, and getAllKeys()
gets all the keys without the data. I could not find a method to get both keys and values.
Isn't there a better way of getting the data and the keys with one call, like it is stored?
If not, is there a nicer way I could do this without making the code too confusing with multiple asynchronous calls happening?
IndexedDB is one of the storage capabilities introduced into browsers over the years. It's a key/value store (a noSQL database) considered to be the definitive solution for storing data in browsers.
Operations performed using IndexedDB are done asynchronously, so as not to block applications.
While IndexedDB makes is possible to store large, nested objects as a single record (and doing so is admittedly quite convenient from a developer perspective), this practice should be avoided.
I was able to retrieve all values with their keys with one callback function using an IDBCursor like this:
transaction = this.db.transaction(["table"]);
object_store = transaction.objectStore("table");
request = object_store.openCursor();
request.onerror = function(event) {
console.err("error fetching data");
};
request.onsuccess = function(event) {
let cursor = event.target.result;
if (cursor) {
let key = cursor.primaryKey;
let value = cursor.value;
console.log(key, value);
cursor.continue();
}
else {
// no more results
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With