Skip to content

Instantly share code, notes, and snippets.

@mehran-prs
Created December 5, 2019 16:07
Show Gist options
  • Save mehran-prs/75f1b87096fec1d7732823d3d352febf to your computer and use it in GitHub Desktop.
Save mehran-prs/75f1b87096fec1d7732823d3d352febf to your computer and use it in GitHub Desktop.
Update object in chrome indexed db (can insert as snippet in chrome snippets)
// usage: update dbName,objectStoreName,keyVal and then update data in updateDoc function,finally return doc.
(function () {
let dbName = "db_name";
let dbVersion = 4
let objectStoreName = "object_store_name"
let keyVal = "object_key_val"
// Change doc and return it.
let getUpdatedDoc = function (doc) {
// TODO: update document here
return doc
}
let db
function openDB(callback) {
let request = indexedDB.open(dbName, dbVersion);
request.onerror = function (event) {
console.log("Why didn't you allow my web app to use IndexedDB?!");
};
request.onsuccess = function (event) {
db = event.target.result;
callback()
}
}
function getObjectStore(objectStoreName) {
return db.transaction([objectStoreName], "readwrite").objectStore(objectStoreName)
}
function updateDoc(key, callback) {
let myObjectStore = getObjectStore(objectStoreName)
let request = myObjectStore.get(keyVal);
request.onerror = function (event) {
console.log("We have some error on getting data", event)
};
request.onsuccess = function (event) {
// Get the old value that we want to update
let doc = event.target.result;
// update the value(s) in the object that you want to change
doc = callback(doc)
console.log(doc)
let updateRequest = myObjectStore.put(doc)
updateRequest.onerror = function (event) {
console.log("We have some error on put data", event)
};
updateRequest.onsuccess = function (event) {
console.log("Data successfully was updated.")
};
};
}
function init() {
updateDoc(keyVal, getUpdatedDoc)
}
openDB(init)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment