On the indexeddb i want to look if there is a key permanent
and do some actions. But if not, i want to make some other actions. I can do the actions if the permanent
is there, however when it is not I can get the onerror to work. Is the onerror
suppose to do this thing? How can I check if there is not value in it?
var hashtype='permanent';
var getPermanent = store.get(hashtype);
getPermanent.onsuccess = function() {
var ivrame=getPermanent.result.value;
};
getPermanent.onerror = function() {
console.log('onerror')
};
See the note under https://w3c.github.io/IndexedDB/#dom-idbobjectstore-get - the get
method yields success with undefined
if there is no matching record.
So you have a few options:
get(key)
and test the result for undefined
. This works unless undefined
is a value you expect to store (it's a valid value)count(key)
- the result will be 1 if present, 0 if absent. Easy if you're just testing for existence, but doesn't get you the record.openCursor(key)
and test to see if the request's result
is a cursor (record present as request.result.value
) or undefined
(no record in range)For your code:
var hashtype='permanent';
// #1: Use get
var getPermanent = store.get(hashtype);
getPermanent.onsuccess = function() {
if (getPermanent.result === undefined) {
// no record with that key
} else {
var value = getPermanent.result;
}
};
// #2: Use count
var getPermanent = store.count(hashtype);
getPermanent.onsuccess = function() {
if (getPermanent.result === 0) {
// no record with that key
} else {
...
}
};
// #3: Use cursor
var getPermanent = store.openCursor(hashtype);
getPermanent.onsuccess = function() {
var cursor = getPermanent.result;
if (!cursor) {
// no record with that key
} else {
var value = cursor.value;
}
};
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