Created
November 9, 2019 12:07
-
-
Save takahirohonda/1f06501b4210a398c9a2b138195a078b to your computer and use it in GitHub Desktop.
replacing-local-storage-with-indexeddb-3-get-data.ts
This file contains hidden or 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
const getReadOnlyStore = () => { | |
// db is defined at the top | |
const request = indexedDB.open('mtd', 1) | |
return new Promise((resolve, reject) => { | |
request.onsuccess = (e: any) => { | |
db = e.target.result | |
const transaction = db.transaction('mtd-data', 'readonly') | |
const store = transaction.objectStore('mtd-data') | |
resolve(store) | |
} | |
request.onerror = (e: any) => { | |
console.error('Failed to open db second time: ', e.target.error) | |
reject(e.target.error) | |
} | |
}) | |
} | |
export const getDataFromIndexedDb = async (key: string) => { | |
try { | |
const store: any = await getReadOnlyStore() | |
console.log('store is ready to getDataFromIndexedDb') | |
const categoryData = store.get(key) | |
return new Promise((resolve, reject) => { | |
categoryData.onsuccess = (e: any) => { | |
console.log('category data retrived: ', e.target.result) | |
resolve(e.target.result) | |
db.close() | |
} | |
categoryData.onerror = (e: any) => { | |
reject(e.target.error) | |
console.error('data retrieval error: ', e.target.error) | |
} | |
}) | |
} catch (e) { | |
console.error('error in getReadOnlySore(): ', e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment