Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if key is not found in IndexedDB?

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')
};
like image 797
villoui Avatar asked May 06 '16 14:05

villoui


1 Answers

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:

  • Use get(key) and test the result for undefined. This works unless undefined is a value you expect to store (it's a valid value)
  • Use 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.
  • Use 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;
    }
};
like image 123
Joshua Bell Avatar answered Sep 18 '22 14:09

Joshua Bell