Google News
logo
JavaScript IndexedDB - Interview Questions
How do "Cursors" work in IndexedDB?
Cursors in IndexedDB are objects used to traverse and interact with the data in object stores and indexes. They allow you to iterate over records, retrieve data from specific ranges, and can navigate in any direction.

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

openRequest.onsuccess = function(e) {
  let db = e.target.result;
  let transaction = db.transaction("books", "readonly");
  let objectStore = transaction.objectStore("books");
  let request = objectStore.openCursor();

  request.onsuccess = function(e) {
    let cursor = e.target.result;
    
    if (cursor) {
      console.log("Key: ", cursor.key);
      console.log("Value: ", cursor.value);
      
      // Continue to the next item
      cursor.continue();
    } else {
      console.log("End of data");
    }
  };

  request.onerror = function(e) {
    console.error("Error opening cursor: ", e.target.errorCode);
  };
};

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