Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

HTML IndexedDB Insert

Posted in HTML Tutorial
Updated on Sep 29, 2024
By Mari Selvan
πŸ‘οΈ 125 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
HTML IndexedDB Insert

Photo Credit to CodeToFun

πŸ™‹ Introduction

IndexedDB is a low-level API for storing large amounts of structured data in the browser. It allows you to create, read, update, and delete data in a transactional manner.

In this guide, we'll focus on how to insert data into an IndexedDB database, which is crucial for applications requiring client-side storage.

❓ What is IndexedDB?

IndexedDB is a database system that allows for the storage of significant amounts of structured data. It supports indexing and transactions and is designed for applications that need to store and retrieve complex data, such as offline web applications.

🎨 Creating an IndexedDB Database

Before inserting data, you need to create an IndexedDB database. This involves defining an object store, which is a structure for storing data. Here's a simple example of creating a database with an object store:

javascript
Copied
Copy To Clipboard
// Create or open a database
const request = indexedDB.open('myDatabase', 1);

request.onupgradeneeded = function(event) {
  const db = event.target.result;
  // Create an object store
  const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id', autoIncrement: true });
  // Define an index on a field
  objectStore.createIndex('nameIndex', 'name', { unique: false });
};

request.onsuccess = function(event) {
  console.log('Database created/opened successfully');
};

request.onerror = function(event) {
  console.error('Database error:', event.target.errorCode);
};

πŸ”“ Opening a Database

Once a database is created, you can open it to perform operations like inserting data. Here’s how to open a database and handle transactions:

javascript
Copied
Copy To Clipboard
const request = indexedDB.open('myDatabase');

request.onsuccess = function(event) {
  const db = event.target.result;
  // Database opened successfully
};

request.onerror = function(event) {
  console.error('Database error:', event.target.errorCode);
};

πŸ“₯ Inserting Data

To insert data into an object store, you need to perform a transaction. Here's how you can add data to the store:

javascript
Copied
Copy To Clipboard
const request = indexedDB.open('myDatabase');

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(['myObjectStore'], 'readwrite');
  const objectStore = transaction.objectStore('myObjectStore');

  // Create an object to store
  const item = { name: 'John Doe', age: 30 };

  const addRequest = objectStore.add(item);

  addRequest.onsuccess = function() {
    console.log('Data added to the store:', item);
  };

  addRequest.onerror = function(event) {
    console.error('Error adding data:', event.target.errorCode);
  };
};

πŸ’Έ Handling Transactions

Transactions in IndexedDB ensure data integrity by grouping operations. You can specify the transaction mode (readwrite or readonly) and handle success and error events accordingly:

javascript
Copied
Copy To Clipboard
const transaction = db.transaction(['myObjectStore'], 'readwrite');

transaction.oncomplete = function() {
  console.log('Transaction completed successfully');
};

transaction.onerror = function(event) {
  console.error('Transaction error:', event.target.errorCode);
};

🚫 Error Handling

Handling errors effectively is crucial for maintaining a robust application. IndexedDB operations can fail due to various reasons, such as exceeding storage limits or trying to perform operations on a closed database:

javascript
Copied
Copy To Clipboard
const request = indexedDB.open('myDatabase');

request.onerror = function(event) {
  console.error('Database error:', event.target.errorCode);
};

const transaction = db.transaction(['myObjectStore'], 'readwrite');

transaction.onerror = function(event) {
  console.error('Transaction error:', event.target.errorCode);
};

⚠️ Common Pitfalls

  1. Data Integrity: Ensure that the key paths and indexes are correctly defined to avoid data inconsistencies.
  2. Database Versioning: Handle database version changes properly using the onupgradeneeded event.
  3. Browser Compatibility: IndexedDB is widely supported but always check for compatibility in different browsers and provide fallbacks if needed.

πŸ“ Example Usage

Here’s a complete example that demonstrates creating a database, adding data, and handling transactions:

HTML
Copied
Copy To Clipboard
<!DOCTYPE html>
<html>
<head>
  <title>IndexedDB Insert Example</title>
</head>
<body>
  <h1>IndexedDB Insert Example</h1>
  <button id="addData">Add Data</button>

  <script>
    // Create or open a database
    const dbRequest = indexedDB.open('myDatabase', 1);

    dbRequest.onupgradeneeded = function(event) {
      const db = event.target.result;
      db.createObjectStore('myObjectStore', { keyPath: 'id', autoIncrement: true });
    };

    dbRequest.onsuccess = function(event) {
      const db = event.target.result;
      
      document.getElementById('addData').addEventListener('click', () => {
        const transaction = db.transaction(['myObjectStore'], 'readwrite');
        const objectStore = transaction.objectStore('myObjectStore');

        const item = { name: 'Jane Doe', age: 25 };
        const addRequest = objectStore.add(item);

        addRequest.onsuccess = function() {
          console.log('Data added:', item);
        };

        addRequest.onerror = function(event) {
          console.error('Error adding data:', event.target.errorCode);
        };
      });
    };

    dbRequest.onerror = function(event) {
      console.error('Database error:', event.target.errorCode);
    };
  </script>
</body>
</html>

πŸŽ‰ Conclusion

Inserting data into IndexedDB involves creating a database, opening it, handling transactions, and managing errors. Mastering these steps ensures efficient and reliable client-side data storage for your web applications.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
11 months ago

If you have any doubts regarding this article (HTML IndexedDB Insert) please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy