Created
October 10, 2023 19:26
-
-
Save chrisbirster/e8f7032239b323dfe5a1f6719f227495 to your computer and use it in GitHub Desktop.
Provides an example of CRUD operations using idb with a Users database for IndexedDB
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
import { openDB} from "idb"; | |
async function setupDatabase() { | |
const db = await openDB('myDatabaseIDB', 1, { | |
upgrade(db) { | |
console.log('Upgrading the database...'); | |
if (!db.objectStoreNames.contains('users')) { | |
console.log('Creating object store...'); | |
db.createObjectStore('users', { keyPath: 'id' }); | |
} | |
} | |
}); | |
console.log('Database opened successfully.'); | |
return db; | |
} | |
async function addUser(db) { | |
const tx = db.transaction('users', 'readwrite'); | |
const users = tx.objectStore('users'); | |
await users.add({ id: 1, name: 'Jill' }); | |
console.log('User added successfully.'); | |
} | |
async function fetchUser(db) { | |
const tx = db.transaction('users', 'readonly'); | |
const users = tx.objectStore('users'); | |
const user = await users.get(1); | |
console.log('Fetched user:', user); | |
} | |
async function updateUser(db) { | |
const tx = db.transaction('users', 'readwrite'); | |
const users = tx.objectStore('users'); | |
await users.put({ id: 1, name: 'Jack' }); | |
console.log('User updated successfully.'); | |
} | |
async function deleteUser(db) { | |
const tx = db.transaction('users', 'readwrite'); | |
const users = tx.objectStore('users'); | |
await users.delete(1); | |
console.log('User deleted successfully.'); | |
} | |
(async function() { | |
const db = await setupDatabase(); | |
await addUser(db); | |
await fetchUser(db); | |
await updateUser(db); | |
await fetchUser(db); | |
await deleteUser(db); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment