Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key of added record in IndexedDB

I have this code in IndexedDB:

var request = objectStore.add({ entryType: entryType, entryDate: t});

Now I want to know the key of this record that was just added in. How do I do that?

I found this article, and this code:

var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
    document.write("Saved with id ", event.result)
    var key = event.result;
};

This does not work for me - key shows up as undefined. I think I am missing something basic here!

like image 495
Stacked Flow Avatar asked Dec 20 '22 11:12

Stacked Flow


2 Answers

Go through this code

var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
    document.write("Saved with id ", event.result)
    var key = event.target.result;
};

Hope this code will work to retrieve key of last inserted Record

like image 117
Vikram Avatar answered Jan 03 '23 03:01

Vikram


The spec is written for user agent, not for developer. So it is confusing. Key generator is provided by the user agent.

Any event object that is received by onsuccess handler always have event.target.result. It is the key you are looking for. The key is auto generated if you don't provide it, assuming you set autoIncrement to true.

It is documented in Step 8: as follow:

  1. The result of this algorithm is key.
like image 21
Kyaw Tun Avatar answered Jan 03 '23 01:01

Kyaw Tun