Back to Freecodecamp

What Is IndexedDB, and How Does It Work?

curriculum/challenges/english/blocks/lecture-working-with-client-side-storage-and-crud-operations/6733ffb59c62ee4a23522efe.md

latest5.4 KB
Original Source

--interactive--

IndexedDB is a tool for storing structured data in the browser. This is built into modern web browsers, allowing web apps to store and fetch JavaScript objects efficiently.

Unlike other storage mechanisms like localStorage, which is limited to storing strings, IndexedDB can store JavaScript objects, files, and pretty much any other type of data. This makes it easy for web applications that need to work with large and complex data structures.

Now, let's look at how IndexedDB works.

The first step is to open a database. Here's an example:

:::interactive_editor

js
let request = indexedDB.open("Sample DB", 1);

request.onerror = function(event) {
  console.log("Error opening database");
};

request.onsuccess = function(event) {
  let db = event.target.result;
  console.log("Database opened successfully");
};

:::

In this code, we're opening a database named "Sample DB" with version 1. We provide two callback functions: one for handling errors, and another for when the database is successfully opened. The db object we get in the success callback is what we'll use to interact with the database.

If you check the browser dev tools application interface, you will see your Sample DB in the IndexedDb section has been opened. Once you have your database open, you can start working with object stores.

Object stores in IndexedDB are similar to tables in traditional databases. They hold the actual data you want to store. Here's how to create an object store:

js
let request = indexedDB.open("Sample DB", 1);

request.onupgradeneeded = function(event) {
  let db = event.target.result;
  let objectStore = db.createObjectStore("customers", { keyPath: "id" });
};

This code creates an object store named "customers" with "id" as its key path. The key path is like a primary key in a traditional database - it's used to uniquely identify each record.

To add data to our object store, we'd do something like this. The db in this example represents the IndexedDB database instance.

js
let transaction = db.transaction(["customers"], "readwrite");
let objectStore = transaction.objectStore("customers");
let request = objectStore.add({ id: 1, name: "John Doe", email: "[email protected]" });

request.onerror = function(event) {
  console.log("Error adding data");
};

request.onsuccess = function(event) {
  console.log("Data added successfully");
};

This code adds a new customer to our "customers" object store. We start a transaction (which is how we group database operations), get a reference to our object store, and then add our data.

Retrieving data works in a similar way. We start a transaction, get our object store, and then use methods like get to retrieve data:

js
let transaction = db.transaction(["customers"]);
let objectStore = transaction.objectStore("customers");
let request = objectStore.get(1);

request.onerror = function(event) {
  console.log("Error retrieving data");
};

request.onsuccess = function(event) {
  console.log("Customer:", request.result);
};

This code retrieves the customer with id of 1 from our "customers" object store.

One of the key features of IndexedDB is that it's asynchronous.

This means that when you interact with IndexedDB, operations don't block the main thread of the web application. This ensures that your web application remains responsive even when dealing with large amounts of data.

While IndexedDB provides powerful capabilities, it has a steeper learning curve compared to other simpler storage API options which can be challenging for beginners. However, for applications that need to handle large amounts of structured data on the client-side, IndexedDB offers unparalleled capabilities.

--questions--

--text--

What is a key characteristic of IndexedDB operations?

--answers--

They are always synchronous.

--feedback--

Consider how IndexedDB operations interact with the main thread of a web application.


They are always asynchronous.


They only work with string data.

--feedback--

Consider how IndexedDB operations interact with the main thread of a web application.


They require a constant internet connection.

--feedback--

Consider how IndexedDB operations interact with the main thread of a web application.

--video-solution--

2

--text--

What is the primary advantage of using IndexedDB over localStorage?

--answers--

IndexedDB is easier to use.

--feedback--

Consider the types of data each storage method can handle and how this affects their use cases.


IndexedDB supports storing complex JavaScript objects directly.


IndexedDB is synchronous.

--feedback--

Consider the types of data each storage method can handle and how this affects their use cases.


IndexedDB is supported in older browsers.

--feedback--

Consider the types of data each storage method can handle and how this affects their use cases.

--video-solution--

2

--text--

In IndexedDB, what is an object store most similar to in traditional relational databases?

--answers--

A database.

--feedback--

Consider how data is organized in IndexedDB compared to a traditional SQL database.


A table.


A row.

--feedback--

Consider how data is organized in IndexedDB compared to a traditional SQL database.


A column.

--feedback--

Consider how data is organized in IndexedDB compared to a traditional SQL database.

--video-solution--

2