IndexedDB: Adding data into a store

Adding data when the store is created, initializing it

You use the put method of the object store, but first we need a reference to it, which we can get from db.createObjectStore() when we create it.

When using put, the value is the first argument, the key is the second. This is because if you specify keyPath when creating the object store, you don’t need to enter the key name on every put() request, you can just write the value.

This populates store0 as soon as we create it:

(async () => {
  //...
  const dbName = 'mydbname'
  const storeName = 'store0'
  const version = 1

  const db = await openDB(dbName, version,{
    upgrade(db, oldVersion, newVersion, transaction) {
      const store = db.createObjectStore(storeName)
      store.put('Hello world!', 'Hello')
    }
  })
})()

Adding data when the store is already created, using transactions

To add items later down the road, you need to create a read/write transaction, that ensures database integrity (if an operation fails, all the operations in the transaction are rolled back and the state goes back to a known state).

For that, use a reference to the dbPromise object we got when calling openDB, and run:

(async () => {
  //...
  const dbName = 'mydbname'
  const storeName = 'store0'
  const version = 1

  const db = await openDB(/* ... */)

  const tx = db.transaction(storeName, 'readwrite')
  const store = await tx.objectStore(storeName)

  const val = 'hey!'
  const key = 'Hello again'
  const value = await store.put(val, key)
  await tx.done
})()

Lessons in this unit:

0: Introduction
1: Loading the idb library
2: Creating a database and a store
3: ▶︎ Adding data into a store
4: Retriving data from a store
5: Deleting data
6: Migrations
7: Unique keys
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!