
{{ $('Map tags to IDs').item.json.title }}
How to Use IndexedDB in the Browser
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It is more powerful than localStorage and allows you to create asynchronous applications. This tutorial will guide you through the basics of using IndexedDB in the browser.
Prerequisites
- Basic knowledge of JavaScript and web development.
- A modern web browser that supports IndexedDB (most modern browsers do).
1. Opening a Database
To start using IndexedDB, you first need to open a database. Use the following code to open a database named myDatabase
:
const request = indexedDB.open('myDatabase', 1);
The second parameter is the version of the database. If a higher version is passed, the onupgradeneeded
event will be triggered.
1.1. Handling Events
You need to handle events during the database operations:
request.onupgradeneeded = function(event) {
const db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
};
request.onsuccess = function(event) {
const db = event.target.result;
console.log('Database opened successfully');
};
request.onerror = function(event) {
console.error('Error opening database:', event.target.errorCode);
};
2. Adding Data to IndexedDB
To add data to your object store, use the add
method:
const addData = (data) => {
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.add(data);
request.onsuccess = function() {
console.log('Data added successfully');
};
request.onerror = function() {
console.error('Error adding data:', request.error);
};
};
You can call addData
with an object:
addData({ id: 1, name: 'John Doe' });
3. Retrieving Data from IndexedDB
To retrieve data, use the get
method:
const transaction = db.transaction(['myObjectStore'], 'readonly');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.get(1);
request.onsuccess = function(event) {
console.log('Data retrieved:', event.target.result);
};
4. Updating Data in IndexedDB
To update an existing record, use the put
method:
const updatedData = { id: 1, name: 'Jane Doe' };
const request = objectStore.put(updatedData);
request.onsuccess = function() {
console.log('Data updated successfully');
};
5. Deleting Data from IndexedDB
To delete data, use the delete
method:
const request = objectStore.delete(1);
request.onsuccess = function() {
console.log('Data deleted successfully');
};
6. Conclusion
IndexedDB provides a powerful way to store data on the client side in web applications. By following this guide, you have learned how to open a database, add, retrieve, update, and delete data using IndexedDB. Explore the extensive capabilities of IndexedDB to enhance your web applications!