IndexedDB

Introduction

Welcome to this lesson on IndexedDB, a critical component in modern web development using JavaScript. IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This allows you to create applications with rich client-side data storage capabilities.

What is IndexedDB?

IndexedDB is a way for you to persistently store data inside a user’s browser. It’s more powerful than other storage options like LocalStorage because it can handle larger amounts of data and supports transactions. It’s an asynchronous API, which means it operates in the background and doesn’t block the browser.

Key Concepts of IndexedDB

  • Database: Like a container for your data.
  • Object Store: Similar to a table in a relational database.
  • Index: Allows efficient data retrieval.
  • Transaction: A series of read/write operations.

Creating and Opening a Database

To start using IndexedDB, you first need to open a database;

javascript
	let db;
	const request = window.indexedDB.open("MyTestDatabase", 1);
	
	request.onerror = function(event) {
	  // Handle errors.
	};
	
	request.onsuccess = function(event) {
	  db = event.target.result;
	};

In this example, MyTestDatabase is the name of the database, and 1 is the version number.

Basic CRUD Operations

Creating Data

To add data, you need to create a transaction and an object store:

javascript
	const customerData = [
	  { id: "444-44-4444", name: "Ola", age: 35, email: "ola@example.com" },
	  { id: "555-55-5555", name: "Kari", age: 32, email: "kari@example.com" }
	];
	
	const transaction = db.transaction(["customers"], "readwrite");
	
	transaction.oncomplete = function(event) {
	  console.log("All done!");
	};
	
	transaction.onerror = function(event) {
	  // Handle errors
	};
	
	const objectStore = transaction.objectStore("customers");
	customerData.forEach(function(customer) {
	  objectStore.add(customer);
	});

Reading Data

To read data, use the get method:

javascript
	const transaction = db.transaction(["customers"]);
	const objectStore = transaction.objectStore("customers");
	const request = objectStore.get("444-44-4444");
	
	request.onerror = function(event) {
	  // Handle errors.
	};
	
	request.onsuccess = function(event) {
	  // Do something with request.result
	};

Updating Data

Updating data is similar to adding data, but you use the put method:

javascript
	const objectStore = db.transaction(["customers"], "readwrite").objectStore("customers");
	const request = objectStore.get("444-44-4444");
	request.onsuccess = function(event) {
	  const data = request.result;
	  data.age = 42;
	  const requestUpdate = objectStore.put(data);
	  requestUpdate.onerror = function(event) {
	    // Handle errors.
	  };
	  requestUpdate.onsuccess = function(event) {
	    // Data updated successfully.
	  };
	};

Deleting Data

To delete data, use the delete method:

javascript
	const request = db.transaction(["customers"], "readwrite")
	                .objectStore("customers")
	                .delete("444-44-4444");
	request.onsuccess = function(event) {
	  // Data deleted.
	};

Practical Example: A Simple To-Do List

Now, let’s implement a simple to-do list using IndexedDB.

Scenario

You want to create a to-do list where users can add and delete tasks. Each task has a unique ID and a description.

Implementation Steps

  1. Create the Database: First, open a database and create an object store for the tasks.

  2. Add Tasks: Implement a function to add tasks to the IndexedDB.

  3. Display Tasks: Read tasks from the database and display them to the user.

  4. Delete Tasks: Allow users to delete tasks.

Code Example

Here’s a simplified version of how you might implement this:

javascript
	// Step 1: Open a database
	let db;
	const request = indexedDB.open("todoList", 1);
	
	request.onupgradeneeded = function(event) {
	  db = event.target.result;
	  const objectStore = db.createObjectStore("tasks", { keyPath: "id" });
	};
	
	request.onsuccess = function(event) {
	  db = event.target.result;
	};
	
	// Step 2: Function to add tasks
	function addTask(id, task) {
	  const transaction = db.transaction(["tasks"], "readwrite");
	  transaction.objectStore("tasks").add({ id: id, task: task });
	}
	
	// Step 3: Function to display tasks
	function displayTasks() {
	  const objectStore = db.transaction("tasks").objectStore("tasks");
	  objectStore.openCursor().onsuccess = function(event) {
	    const cursor = event.target.result;
	    if (cursor) {
	      console.log("Task ID: " + cursor.key + ", Task: " + cursor.value.task);
	      cursor.continue();
	    }
	  };
	}
	
	// Step 4: Function to delete tasks
	function deleteTask(id) {
	  const request = db.transaction(["tasks"], "readwrite")
	                    .objectStore("tasks")
	                    .delete(id);
	  request.onsuccess = function(event) {
	    console.log("Task deleted");
	  };
	}

Conclusion

IndexedDB is a powerful tool for web developers, enabling the creation of sophisticated, data-rich web applications. By mastering the basics of IndexedDB and understanding how to perform CRUD operations, you’re well on your way to leveraging this technology in your web projects.