Introduction to idb
idb stands for IndexedDB, a low-level API for client-side storage of significant amounts of structured data. It makes it easy for developers to perform database operations on the web browser like inserting, updating, querying, and deleting data in a transactional way.
Getting Started with idb
import { openDB } from 'idb'; const db = await openDB('my-database', 1, { upgrade(db) { db.createObjectStore('store'); }, });
Basic CRUD Operations
Create
await db.put('store', { name: 'John Doe', age: 30 }, '1');
Read
const data = await db.get('store', '1'); console.log(data); // { name: 'John Doe', age: 30 }
Update
await db.put('store', { name: 'John Doe', age: 31 }, '1');
Delete
await db.delete('store', '1');
Working with Indexes
Indexes can be used to optimize data lookup operations. Here’s how you can create and use indexes in idb:
const db = await openDB('my-database', 2, { upgrade(db) { const store = db.createObjectStore('store', { keyPath: 'id' }); store.createIndex('name', 'name'); store.createIndex('age', 'age'); }, }); const tx = db.transaction('store', 'readonly'); const store = tx.objectStore('store'); const index = store.index('name'); const data = await index.get('John Doe'); console.log(data); // Outputs objects matching the name 'John Doe'
Transactions
Understanding and using transactions properly can significantly boost the performance and reliability of your application:
const tx = db.transaction('store', 'readwrite'); const store = tx.objectStore('store'); store.put({ id: 1, name: 'John Doe', age: 30 }); store.put({ id: 2, name: 'Jane Doe', age: 25 }); await tx.done;
Sample Application
Here is an example of a simple application using many of the idb APIs we discussed:
import { openDB } from 'idb'; const db = await openDB('app-database', 1, { upgrade(db) { const store = db.createObjectStore('users', { keyPath: 'id' }); store.createIndex('name', 'name'); }, }); document.querySelector('#form').addEventListener('submit', async event => { event.preventDefault(); const id = document.querySelector('#id').value; const name = document.querySelector('#name').value; await db.put('users', { id, name }); alert('User added!'); }); document.querySelector('#search').addEventListener('input', async event => { const name = event.target.value; const index = db.transaction('users').store.index('name'); const user = await index.get(name); document.querySelector('#result').textContent = user ? `Found: ${user.name}` : 'No user found'; });
With these basics and examples, you can now start developing your own applications with IndexedDB and the idb library.
Hash: 695306d7e5ed69cd322c0c20a3c8db36f605b25bfdf176905753dc9f1be47258