Last active
June 10, 2023 11:38
-
-
Save tobiashm/5f4062eefb00a5b46ad3748958eaabdc to your computer and use it in GitHub Desktop.
Read a singe key value from IndexedDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assuming https://github.com/jakearchibald/idb-keyval has been used for key-value entries, | |
// the following is about the minimum code needed to read the value for a single key (w/o the lib.) | |
// Usage: `readKey('name').then(function(name) { console.log(name); });` | |
function readKey(key) { | |
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB; | |
if (!indexedDB) return Promise.reject(new Error('IndexedDB not available')); | |
return new Promise(function(resolve, reject) { | |
var open = indexedDB.open('keyval-store', 1); | |
open.onerror = function () { | |
reject(open.error); | |
}; | |
open.onupgradeneeded = function () { | |
open.result.createObjectStore('keyval'); | |
}; | |
open.onsuccess = function() { | |
var db = open.result; | |
var tx = db.transaction('keyval', 'readonly'); | |
var store = tx.objectStore('keyval'); | |
var getKey = store.get(key); | |
getKey.onsuccess = function() { | |
resolve(getKey.result); | |
}; | |
tx.onerror = function () { | |
reject(tx.error); | |
}; | |
tx.oncomplete = function () { | |
db.close(); | |
}; | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment