IndexedDB example and how is it different to localstorage
IndexedDB persist data across sessions, just like localStorage
. However, there are some key differences between IndexedDB and localStorage
that make IndexedDB more powerful and flexible for certain use cases. Here’s an overview of IndexedDB and how it compares to localStorage
:
IndexedDB Overview
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It is a transactional database system, like an SQL-based RDBMS, but with a key-value store structure instead of a relational table structure. IndexedDB allows for more complex data storage and retrieval than localStorage
.
Persistence
- Persistence Across Sessions: IndexedDB data persists across sessions. This means that the data you store in IndexedDB remains available even after the browser is closed and reopened, as long as the user doesn't clear their browser data.
- Size Limits: IndexedDB can store much larger amounts of data compared to
localStorage
, which is typically limited to around 5-10 MB per origin (depending on the browser).
Advantages Over localStorage
- Structured Data: IndexedDB can store complex data structures, including objects and arrays, which can be indexed and queried efficiently.
- Asynchronous API: IndexedDB operations are asynchronous and non-blocking, which means they don't hinder the performance of your web app. In contrast,
localStorage
operations are synchronous and can block the main thread. - Transactions: IndexedDB supports transactions, allowing for reliable and consistent data operations.
- Large Storage: IndexedDB is suitable for storing larger amounts of data, such as images, videos, and other media, unlike
localStorage
, which is limited in storage capacity.
Example Usage of IndexedDB
Here is a basic example of how to use IndexedDB in a web application:
1. Open or Create a Database
const request = indexedDB.open('MyDatabase', 1);
request.onerror = function(event) {
console.error('Database error:', event.target.errorCode);
};
request.onsuccess = function(event) {
const db = event.target.result;
console.log('Database opened successfully');
};
request.onupgradeneeded = function(event) {
const db = event.target.result;
const objectStore = db.createObjectStore('MyObjectStore', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
};
2. Add Data to the Database
function addData(db) {
const transaction = db.transaction(['MyObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('MyObjectStore');
const request = objectStore.add({ id: 1, name: 'John Doe', email: '[email protected]' });
request.onsuccess = function(event) {
console.log('Data has been added to your database.');
};
request.onerror = function(event) {
console.error('Unable to add data:', event.target.errorCode);
};
}
// Assuming `db` is the opened database instance
addData(db);
3. Retrieve Data from the Database
function getData(db, id) {
const transaction = db.transaction(['MyObjectStore']);
const objectStore = transaction.objectStore('MyObjectStore');
const request = objectStore.get(id);
request.onsuccess = function(event) {
if (request.result) {
console.log('Data retrieved:', request.result);
} else {
console.log('No data record found for id:', id);
}
};
request.onerror = function(event) {
console.error('Unable to retrieve data:', event.target.errorCode);
};
}
// Assuming `db` is the opened database instance
getData(db, 1);
4. Delete Data from the Database
function deleteData(db, id) {
const transaction = db.transaction(['MyObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('MyObjectStore');
const request = objectStore.delete(id);
request.onsuccess = function(event) {
console.log('Data deleted successfully');
};
request.onerror = function(event) {
console.error('Unable to delete data:', event.target.errorCode);
};
}
// Assuming `db` is the opened database instance
deleteData(db, 1);
Published on: Jul 25, 2024, 02:35 AM