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);
};
};
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);
};
};
Solved. You can get the incremented id by using request.result
.
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