Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return auto increment id from objectstore.put() in an IndexedDB?

How do I return the auto incremented ID after inserting a record into an IndexedDB using objectstore.put()?

Below is my code:

idb.indexedDB.addData = function (objectStore, data) {
    var db = idb.indexedDB.db;
    var trans = db.transaction([objectStore], READ_WRITE);
    var store = trans.objectStore(objectStore);
 
 
 
    var request = store.put(data);
    request.onsuccess = function (e) {
        //Success, how do I get the auto incremented id?
    };
    request.onerror = function (e) {
        console.log("Error Adding: ", e);
    };
};
like image 965
joe Avatar asked Sep 19 '12 21:09

joe


2 Answers

Use e.target.result. Since the API is async, you must use callback to get the return value, as follow:

idb.indexedDB.addData = function (objectStore, data, callback) {
    var db = idb.indexedDB.db;
    var trans = db.transaction([objectStore], READ_WRITE);
    var store = trans.objectStore(objectStore);
      
    var request = store.put(data);
    request.onsuccess = function (e) {
        callback(e.target.result);
    };
    request.onerror = function (e) {
        console.log("Error Adding: ", e);
        callback(undefined);
    };
};
like image 164
Kyaw Tun Avatar answered Oct 06 '22 01:10

Kyaw Tun


Solved. You can get the incremented id by using request.result.

like image 40
joe Avatar answered Oct 06 '22 00:10

joe