Chapter 5. IndexedDB

Introduction

Chapter 2 covered data persistence with local or session storage. This works well for string values and serializable objects, but querying is not ideal and objects require JSON serialization. IndexedDB is a newer, more powerful data persistence mechanism present in all modern browsers. An IndexedDB database contains object stores (sort of like tables in a relational database). Each object store can have indexes on certain properties for more efficient querying. It also supports more advanced concepts like versioning and transactions.

Object Stores and Indexes

An IndexedDB database has one or more object stores. All operations to add, remove, or query data are done on an object store. An object store is a collection of JavaScript objects that are persisted in the database. You can define indexes on an object store. An index stores extra information to the database that lets you query objects by the indexed property. For example, suppose you are creating a database to store product information. Each product has a key, likely a product ID or SKU code. This lets you quickly search the database for a given product.

If you want to also be able to query the data by price, you can create an index on the price property. This lets you look up objects by their price. With an index, you can specify a specific price or a range of prices, and the index can quickly find those records for you.

Keys

Objects in a store have a key that uniquely identifies that ...

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.