Retrieving Data by Key
What you'll learn: How to fetch individual records directly from an IndexedDB object store using their primary key.
Once you've added data to an IndexedDB object store, you need a way to pull it back out. The most direct method is using the get() method, which retrieves a single record when you know its primary key.
How It Works
Think of get() like looking up a word in a dictionary — if you know the exact word (the key), you can flip straight to its definition (the stored data) without reading every page.
To retrieve data, you:
- Open a transaction (read-only is fine for fetching)
- Access the object store
- Call
get()with the primary key - Handle the result in a success event handler
Here's the pattern:
const transaction = db.transaction(['myStore'], 'readonly');
const store = transaction.objectStore('myStore');
const request = store.get(123); // 123 is the primary key
request.onsuccess = function(event) {
const data = event.target.result;
if (data) {
console.log('Found:', data);
} else {
console.log('No record found with that key');
}
};
request.onerror = function() {
console.error('Error retrieving data');
};
Key Points
get()returns one record or undefined if the key doesn't exist- The key must match the exact type (number vs string matters)
- Check if
resultexists before using it — IndexedDB won't throw an error for missing keys - Read-only transactions are sufficient for retrieval
Key Takeaway: Use the get() method with a primary key to directly fetch individual records from an IndexedDB object store — it's the fastest way to retrieve known data.