Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

List Items In An IndexedDB Database

NOTE

After writing this I found:

which I'm experimenting with and looks like I'll be using:

See The Stuff

This is how I'm getting a list of all the items for a specific data store in an IndexedDB database. Check the console for the output

JavaScript

let db

const DB_NAME = "Example_List_Items"
const DB_VERSION = 56
const DB_STORE_NAME = `widgets${DB_VERSION}`
const DB_STORE_KEY = "id"

const addItems = () => {
  console.log("adding items")
  const items = [
    { id: "alfa" }, 
    { id: "bravo" }, 
    { id: "charlie" },
    { id: "delta" },
  ]
  const transaction = db.transaction(DB_STORE_NAME, "readwrite")
  const objectStore = transaction.objectStore(DB_STORE_NAME)
  items.forEach((item) => {
    console.log(item)
    const request = objectStore.add(item)
    request.onerror = (event) => {
      console.error(event.target.error)
    }
  })
}

const listItems = () => {
  const objectStore = db.transaction(DB_STORE_NAME).objectStore(DB_STORE_NAME);
  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      console.log(`Widget: ${cursor.key}`)
      console.log(cursor.value)
      cursor.continue()
    }
  }
}

const populateProcess = () => {
  const openRequest = indexedDB.open(DB_NAME, DB_VERSION)
  openRequest.onblocked = (event) => {
    console.error("ERROR: Other tabs migth be open with the DB");
  };
  openRequest.onsuccess = (event) => {
    db = event.target.result
    listItems()
  }
  openRequest.onupgradeneeded = (event) => {
    db = event.target.result
    const objectStore = db.createObjectStore(DB_STORE_NAME, { keyPath: DB_STORE_KEY});
    objectStore.transaction.oncomplete = () => {
      addItems()
    }
  }
}

document.addEventListener("DOMContentLoaded", async () => {
  populateProcess()
})

References

  • This post has a lot in it, but it's structure didn't work very well for me. I've had to pull things out and make my own examples to figure out how things work

  • Docs about the connection for an IndexedDB. I was trying to figure out if `.success()`` is called after `.upgradeneeded()``. I didn't see that in the docs, but that seems to be how things are working with the code

  • There's a bunch of stuff in here that I want to look at for things like how to clear storage. It has `$`` in front of somethings. Not sure if that means it's jQuery or not. I don't see that called, so I'm not sure