Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

List Items In An IndexedDB Database

NOTE

After writing this I found :

> https : //github.com/jakearchibald/idb > https : //github.com/jakearchibald/idb >

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()
})

- This page populates the data so there's something to list

- The main focus of this page is the [TODO: Code shorthand span ] function that expects a [TODO: Code shorthand span ] variable to be available with an open database connection

- Took a while to figure this one out. I'm still a yellow belt with IndexedDB so feel free to check my work

Footnotes And References