Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save takahirohonda/7448fbc752f39e4f6b3f3c692d257601 to your computer and use it in GitHub Desktop.
Save takahirohonda/7448fbc752f39e4f6b3f3c692d257601 to your computer and use it in GitHub Desktop.
replacing-local-storage-with-indexeddb-3-insert-data.ts
export const insertRecordToIndexedDb = (data: any, key: string) => {
let db
const request = indexedDB.open('mtd', 1)
return new Promise((resolve, reject) => {
request.onsuccess = (e: any) => {
db = e.target.result
console.log('opened indexedDb to upsert...', db)
if (db.objectStoreNames.contains('mtd-data')) {
const transaction = db.transaction('mtd-data', 'readwrite')
const store = transaction.objectStore('mtd-data')
store.put(data, key)
console.log('Upserted data: ', data)
db.close()
resolve(true)
}
else {
console.log('mtd-data store already exists')
resolve(true)
}
}
request.onerror = (e: any) => {
console.error('Failed to open db: ', e.target.error)
reject(e.target.error)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment