Sling Academy
Home/JavaScript/Using IndexedDB with JavaScript: CRUD Example

Using IndexedDB with JavaScript: CRUD Example

Last updated: February 14, 2024

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!

Next Article: Enhancing User Engagement with the JavaScript Badging API

Previous Article: CacheStorage in JavaScript: A Practical Guide (with Examples)

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration