Skip to content

Instantly share code, notes, and snippets.

Last active September 10, 2021 20:39
Show Gist options
  • Save maracko/86f912700bda42469975341702ad850b to your computer and use it in GitHub Desktop.
Save maracko/86f912700bda42469975341702ad850b to your computer and use it in GitHub Desktop.
JS indexedDB basics
// Basic pattern
// 1. open a database.
// 2. create an object store in the database.
// 3. start a transaction and make a request to do some database operation, like adding or retrieving data.
// 4. wait for the operation to complete by listening to the right kind of dom event.
// 5. do something with the results (which can be found on the request object).
//Init indexedDB
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (!window.indexedDB) {
//1 is revision, when using new version must increment
let request ="dbName",1),
//defining empty variables
store, //structure for data
//onupgradeneeded fires when a new revision is created
request.onupgradeneeded = function(e){
let db = request.result,
//Instead of {keyPath:""} we can use {autoIncrement:true}
store = db.createObjectStore("storeName",{keyPath: "indexKeyName"}),
index = store.createIndex("indexName","indexKeyName",{unique:false});
//db handlers
request.onerror = function(e) {
console.log("Error :",;
//if and after onupgradeneeded is done, onsuccess fires
request.onsuccess = function(e) {
db = request.result;
tx = db.transaction("storeName","readwrite");
store = tx.objectStore("storeName");
index = store.index("indexName");
index = store.index("key"); //example
db.onerror = function(e){
console.log("ERROR" +;
//inserting data
//retrieving data
let q1 = store.get(1); //Get value by ID
let qs = index.get("value"); //Get value by index
//indexedDb is async so we gotta treat it as such
q1.onsuccess = function(){
qs.onsuccess = function(){
//deleting data. To delete we use the index
let del = store.delete("value");
del.onsuccess = function(e){
console.log("Value sucessfully deleted");
//this is used at end of every transaction
tx.oncomplete = function(){
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment