Last active
September 10, 2021 20:39
-
-
Save maracko/86f912700bda42469975341702ad850b to your computer and use it in GitHub Desktop.
JS indexedDB basics
This file contains 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
// 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) { | |
alert(); | |
} | |
//1 is revision, when using new version must increment | |
let request = window.indexedDB.open("dbName",1), | |
//defining empty variables | |
db, | |
tx, | |
store, //structure for data | |
index; | |
//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 :",e.target.errorCode); | |
}; | |
//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" + e.target.errorCode); | |
} | |
//inserting data | |
store.put({id:1,key:"value",otherKey:"otherValue"}); | |
//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(){ | |
console.log(q1.result); | |
console.log(q1.result.key); | |
}; | |
qs.onsuccess = function(){ | |
console.log(qs.result.key); | |
}; | |
//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(){ | |
db.close(); | |
}; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment