IndexedDB: Creating a database and a store

Before using the IndexedDB API, always make sure you check for support in the browser. Even though IndexedDB is widely available nowadays, you never know which browser the user is using.

Here’s how to check for it, using 'indexedDB' in window:

(() => {
  'use strict'

  if (!('indexedDB' in window)) {
    console.warn('IndexedDB not supported')
    return
  }

  //...we can safely run IndexedDB code
})()

When we create a database, we must initialize a store. If you are familiar with relational databases like MySQL, a store is like a table.

(async () => {
  //...

  const dbName = 'mydbname'
  const storeName = 'store1'
  const version = 1

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

You can check if an object store already exists before creating it, by calling the objectStoreNames() method:

const storeName = 'store1'

if (!db.objectStoreNames.contains(storeName)) {
  db.createObjectStore(storeName)
}

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!