Using IndexedDB with JavaScript: CRUD Example

Updated: February 14, 2024 By: Guest Contributor Post a comment

Introduction

Learn how to leverage IndexedDB with JavaScript through a comprehensive CRUD example, enhancing your application’s storage capabilities.

Getting Started with IndexedDB

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. It allows you to create, read, update, and delete (CRUD) operations on records in a database. Unlike localStorage, which stores data in key-value pairs, IndexedDB supports transactions and can handle large data sets efficiently.

Why IndexedDB?

  • Stores large amounts of data securely and efficiently.
  • Works asynchronously, making it suitable for web applications.
  • Supports complex data types such as files/blobs.
  • Provides rich query capabilities.
  • Operates within the user’s browser, offering offline capabilities.

Setting Up IndexedDB

To work with IndexedDB, you first need to open a connection to a database. This involves specifying the database name and the version. If the database does not exist, it will be created.

const request = indexedDB.open('myDatabase', 1);

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

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

Creating Object Stores and Transactions

Once you have a connection, you can create object stores (similar to tables in relational databases) and manage data using transactions. Let’s create an object store with a simple structure:

request.onupgradeneeded = function(event) {
  const db = event.target.result;
  const store = db.createObjectStore('notes', {keyPath: 'id', autoIncrement: true});
  // Create indices if needed...
};

CRUD Operations

Now, let’s dive into the CRUD operations using this simple ‘notes’ object store as an example.

Creating Items

function createNote(db, note) {
  const transaction = db.transaction(['notes'], 'readwrite');
  const store = transaction.objectStore('notes');
  const request = store.add(note);

  request.onsuccess = function() {
    console.log('Note added:', request.result);
  };

  request.onerror = function() {
    console.error('Error adding note:', request.error);
  };
}

Reading Items

function readNote(db, id) {
  const transaction = db.transaction(['notes'], 'readonly');
  const store = transaction.objectStore('notes');
  const request = store.get(id);

  request.onsuccess = function() {
    console.log('Note read:', request.result);
  };
}

Updating Items

function updateNote(db, note) {
  const transaction = db.transaction(['notes'], 'readwrite');
  const store = transaction.objectStore('notes');
  const request = store.put(note);

  request.onsuccess = function() {
    console.log('Note updated:', request.result);
  };
}

Deleting Items

function deleteNote(db, id) {
  const transaction = db.transaction(['notes'], 'readwrite');
  const store = transaction.objectStore('notes');
  const request = store.delete(id);

  request.onsuccess = function() {
    console.log('Note deleted');
  };
}

Putting It All Together

For a comprehensive example, let’s connect to a database, create an object store (if it doesn’t exist), and perform some CRUD operations:

// Connect to the database
const request = indexedDB.open('myNoteApp', 1);

request.onupgradeneeded = function(event) {
  const db = event.target.result;
  if (!db.objectStoreNames.contains('notes')) {
    db.createObjectStore('notes', {keyPath: 'id', autoIncrement: true});
  }
};

request.onsuccess = function(event) {
  const db = event.target.result;
  // Perform CRUD operations here
};

Conclusion

This guide showcased how to use IndexedDB with JavaScript for sophisticated data management in web applications. Explore and innovate your storage solutions!