Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexedDB getting all data with keys

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.

  1. Isn't there a better way of getting the data and the keys with one call, like it is stored?

  2. If not, is there a nicer way I could do this without making the code too confusing with multiple asynchronous calls happening?

like image 733
TheMechanic Avatar asked Dec 21 '17 19:12

TheMechanic


People also ask

Is IndexedDB key-value?

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.

Is IndexedDB asynchronous?

Operations performed using IndexedDB are done asynchronously, so as not to block applications.

Is it safe to use IndexedDB?

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.


1 Answers

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
   }
};
like image 162
TheMechanic Avatar answered Sep 22 '22 13:09

TheMechanic