Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 57 - IndexedDB: Introduction to a More Powerful Storage

While localStorage and sessionStorage are great for storing small amounts of data, they have limitations. They:

  • Only store data as strings
  • Have a storage limit (about 5MB)
  • Can't store structured data like objects efficiently

Enter IndexedDB!

IndexedDB is a low-level NoSQL database built into the browser that allows storing large amounts of structured data.

Key Features of IndexedDB

  • Stores structured data (objects, arrays, blobs, etc.)
  • Uses object stores instead of key-value pairs
  • Works asynchronously, so it doesn’t block the main thread
  • Supports transactions for data integrity

Creating an IndexedDB Database

Let's create a simple IndexedDB database and store some data.

// Open (or create) a database
let db;
const request = indexedDB.open("MyDatabase", 1);

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

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

Explanation:

  • indexedDB.open("MyDatabase", 1) creates a database called MyDatabase (or opens it if it exists).
  • The 1 is the version number of the database.

Creating an Object Store

Before adding data, we need an object store (like a table in SQL).

request.onupgradeneeded = function (event) {
    let db = event.target.result;

    // Create an object store named "users"
    let store = db.createObjectStore("users", { keyPath: "id" });

    console.log("Object store created!");
};

Key Points:

  • onupgradeneeded runs only when creating or upgrading the database.
  • createObjectStore("users", { keyPath: "id" }) makes a store called "users" with "id" as the unique key.