Skip to content

Instantly share code, notes, and snippets.

@alexjoverm
Created July 28, 2017 14:46
Show Gist options
  • Save alexjoverm/a17fc3aacc8c2a33d6105b9a1abd5eba to your computer and use it in GitHub Desktop.
Save alexjoverm/a17fc3aacc8c2a33d6105b9a1abd5eba to your computer and use it in GitHub Desktop.
let openRequest = indexedDB.open("test", 5);
let messages = [
{ id: 0, message: 'pepepe' },
{ id: 1, message: 'paco' },
]
openRequest.onsuccess = function(ev) {
console.log('SUCCESS')
console.log(ev)
let db = ev.target.result
add(db, messages[0])
add(db, messages[1])
setTimeout(() => {
read(db)
}, 200)
}
openRequest.onupgradeneeded = function(ev) {
console.log('UPGRADED NEEDED')
console.log(ev)
let db = ev.target.result
// If objectStore exists, we'll recreate it
if (db.objectStoreNames.contains('messages')) {
db.deleteObjectStore('messages')
}
db.createObjectStore('messages', { keyPath: 'id' })
}
function add(db, obj) {
let messageStore = db.transaction("messages", "readwrite").objectStore('messages')
messageStore.add(obj)
}
function read(db) {
let store = db.transaction("messages").objectStore('messages')
let request = store.getAll()
request.onsuccess = function(e) {
console.log(e.target.result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment