Google News
logo
JavaScript IndexedDB - Interview Questions
What components do we need to store data in an IndexedDB database?
To store data in an IndexedDB database, you need the following components: database object, object store, key for records, transaction for data operations, and requests to perform CRUD operations on the data.
Technical Details: To store something in IndexedDB, we need an object store.

An object store is a core concept in IndexedDB. Counterparts in other databases are called “tables” or “collections”, where the data is stored. A database may have multiple stores: one for users, another for goods, and more. Despite being named an “object-store” IndexedDB, primitives get stored too.

Code Example :
let openRequest = indexedDB.open("myDatabase", 1);

openRequest.onupgradeneeded = function(e) {
  let db = e.target.result;

  // Create an object store named "books" with "isbn" as the key path
  let store = db.createObjectStore("books", { keyPath: "isbn" });
};

openRequest.onsuccess = function(e) {
  let db = e.target.result;

  // Start a transaction on the "books" object store
  let transaction = db.transaction("books", "readwrite");
  let store = transaction.objectStore("books");

  // Add a book to the object store
  let book = { isbn: "9781234567890", title: "Sample Book" };
  let request = store.add(book);

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

  request.onerror = function(event) {
    console.error("Error adding book:", event.target.errorCode);
  };

  // Commit the transaction
  transaction.oncomplete = function() {
    console.log("Transaction completed");
  };

  transaction.onerror = function(event) {
    console.error("Transaction error:", event.target.errorCode);
  };

  // Close the database connection
  db.close();
};

openRequest.onerror = function(e) {
  console.error("Unable to open database:", e.target.errorCode);
};?
Advertisement