Working with IndexedDB
•
When searching for indexedDB on google, the top search results don't provide a good introduction to indexedDB. So I thought it might help others who want to persist some data in the browser (and avoid hitting the limit of localStorages 5 Mb size cap) to more easily get started.
So if you're looking to copy-paste some CRUD code to get started with IndexedDB, copy the code from example.
Table of Contents
Background
IndexedDB is a database built into the browser and a much more powerful storage solution than localStorage.
- Support for JSON data types as well as additional ones like Date.
- Support for traditional transactions.
- Supports indexing and key range queries.
- Supports cursors for iterating large data sets.
Concepts
- Database: A database is a collection of Object Stores. Similar to a database in a relational database. It's the highest level concept in IndexedDB.
- Object Store: An Object Store is a collection of Objects. Similar to tables in a relation database.
- Object: An object belongs to an Object Store. It's similar to rows in a relational database.
- Index: Allows one to query on properties other than the primary key. Also useful when you want to add a unique constraint on a property.
- Transaction: A unit of work. Allows you to perform multiple modifications to a database with consistency. During a transaction, the Object Store is locked so no other part can modify the Object Store. Transactions also have the property that if one of the modifications fail, then all other modifications in the transaction will be rolled back to its previous state.
- keyPath: A unique id for Objects. Same as Primary Key in relational databases.
Gotcha's
- You use the
open
method to create and open a database (the method creates a database if the database doesn't exist). The database version passed to the database is used as a version of your database, not the database's actual IndexedDB version. - The callback
upgrade
is used to initialize your database schema, as well as to handle migrations between different versions of your database. - IndexedDB does not enforce consistent types for Objects in the same Object Store.
Example
This example uses the async/await wrapper library idb.