Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
IndexedDB how to delete the last entry in a list?

(found on the following website https://javascript.info/indexeddb#object-store) This JavaScript function uses indexeddb to add a book, with data, to a list. The functions allow the user to also delete all the data in the list as well as display the data.

<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/idb@3.0.2/build/idb.min.js"></script>

<button onclick="addBook()">Add a book</button>
<button onclick="clearBooks()">Clear books</button>

<p>Books list:</p>

<ul id="listElem"></ul>

<script>
let db;

init();

async function init() {
  db = await idb.openDb('booksDb', 1, db => {
    db.createObjectStore('books', {keyPath: 'name'});
  });

  list();
}

async function list() {
  let tx = db.transaction('books');
  let bookStore = tx.objectStore('books');

  let books = await bookStore.getAll();

  if (books.length) {
    listElem.innerHTML = books.map(book => `<li>
        name: ${book.name}, price: ${book.price}
      </li>`).join('');
  } else {
    listElem.innerHTML = '<li>No books yet. Please add books.</li>'
  }


}

async function clearBooks() {
  let tx = db.transaction('books', 'readwrite');
  await tx.objectStore('books').clear();
  await list();
}

async function addBook() {
  let name = prompt("Book name?");
  let price = +prompt("Book price?");

  let tx = db.transaction('books', 'readwrite');

  try {
    await tx.objectStore('books').add({name, price});
    await list();
  } catch(err) {
    if (err.name == 'ConstraintError') {
      alert("Such book exists already");
      await addBook();
    } else {
      throw err;
    }
  }
}

window.addEventListener('unhandledrejection', event => {
  alert("Error: " + event.reason.message);
});

</script>

From this script, How would I be able to modify it such that it only removes the last element added to the list? Example if the list was

name: Star wars, price: 20
name: LOTR, price: 30
name: Harry Potter, price: 15

The last entry, Harry Potter, would be deleted?

This was my attempt using removeChild(), however this implementation removes all the data

$('#lastUser').on('click', function() {
  var user = $('#search').val();  
async function clearlastUser() {
  let tx = db.transaction('books', 'readwrite');
  await tx.objectStore('books').parentNode.removeChild(user);
  await list();
}
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

On the page for the library idb here, it shows an example of the delete method. Using this to put something together I would do something like this:

  let db;
  let idx;// declare variable for index of books

  init();

  async function init() {
    db = await idb.openDb("booksDb", 1, (db) => {
      db.createObjectStore("books", { keyPath: "name" });
    });
    list();
    idx = []; //define array to store keys
  }

  async function clearBooks() {
    let tx = db.transaction("books", "readwrite");
    await tx.objectStore("books").clear();
    await list();
    idx = []; //clear index
  }

  async function deleteBook(key) {
    key = idx[idx.length - 1]; //last key added to index
    let tx = db.transaction("books", "readwrite");
    await tx.objectStore("books").delete(key);
    await list();
  }

  async function addBook() {
    let name = prompt("Book name?");
    let price = +prompt("Book price?");

    let tx = db.transaction("books", "readwrite");
      
    await tx.objectStore("books").add({ name, price });
    await list();
    idx.push(name);//add key to index
}

Taking a look at this post here it seems like getting the last item of a JavaScript object is not always accurate and arrays are a better solution. You may want to look there for yourself though because I didn't read it in-depth.

Looking at your example though if the database starts empty then you can create an index of each book in the database to track there order. You can then access the array to get the corresponding key. So for example idx[0] is the name/key to the first book added to the database.

All this being said I'm not very familiar with handling data so there may be a better solution or one built-in to the library you're using. I would encourage you to look into the documentation: https://www.npmjs.com/package/idb/v/3.0.2

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!