TLDR; link below has code needed for the common IndexedDB functions.
My next web app doesn’t need an external database- I only need a local solution. I need something more powerful than Local Storage and brief research showed that Web SQL will no longer be supported.
I decided to use IndexedDB. While there’s plenty of tutorials and articles out there, I couldn’t find a single solution that demonstrated all of the functionality I would need:
- Google has a good explanation of how to use IndexedDB, but at the time of writing, there’s a big banner at the top saying “some of the content may be out of date.”
- An article on Tutorials Point came close to what I needed, but it didn’t show how to use the indexes (i.e. a slightly fancier query).
- An article by Raymond Camden filled in the missing features I needed.
I still wanted to have a single consolidated template for all IndexedDB functionality. I created that, and am sharing it now.
Similar to a relational database, I created two tables (known as “objects”). I modified my code sample to be more generic, so I renamed these objects as “Shows” (as in television shows) and “People” (as in the characters).
For this code sample, the data is hard-coded within each function: as if it were extracted from an HTML form element (for example, by the “id”). For my actual application, I’ll be passing data into the functions — but the principle is the same.
To see it in action: upon clicking a button, the results of each database operation (“transaction”) appears in the browser’s Developer Console.
I’m using Google Chrome. Open the Developer Console (keyboard shortcut on Windows is F12). In the Application tab, you’ll see a spot for “IndexedDB”. If needed, delete/refresh the specific database. Note, changes made in this view are not visible real-time and you’ll need to refresh to see said changes. Viewing the results in the Console is therefore much more convenient.
Alright, so where’s the code?!
View the demo here: https://stevesohcot.github.io/indexeddb . Be sure to have your browser Developer Console open.
View the code by looking at the Page Source in the link above, or you can see it here: https://github.com/stevesohcot/indexeddb/blob/master/index.html