Storing data with IndexedDB for service workers and PWAs

PWA’s will need persistent storage sometimes but it is damn painful to do without studying indexedDB — so I did it for you

The key challenge — Async interactions

This is a problem I have hit a few times. You can’t just get data from the db by stating it — ie. const value = db.value. This is different for most of us.

Instead we need to say that we want it, and then say what we will do with it after it comes back — callbacks.

Mozilla talks about a common pattern to bear in mind while interacting:

https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

The code should be structured similarly.

Prep work

For the gists below to work you will need to define a few things. Specifically:

const dbName = "whateverYouWant";const version = 1; // incremental intsconst storeName = "whateverYouLike";let db; // define the db variable to be global in the sw file

Open a db and create the object store

Remember it is async, so we need to request and then respond depending on the response. There can be three responses — error, success, or upgrade needed.

Also note, we create the object store here — and upgrade is needed if there is no previous store! Here we define what should be the primary key of the objectStore.

Create transaction and add to the store

Next we want define a transaction on the particular objectStore we want to change.

A transaction is essentially a declaration of what you want to do. The db will do these instructions, see if it would fail or succeed, and then only do the actions if they would pass — this is a dummies guide, they are much more complicated.

Wait then do

The next action you will want to do is read from the inedxedDB. We can do this but we cannot forget about callbacks once again.

You cannot do this:

const dataFromStore = getDataFromStore(key)

You instead need to request for data, and then run a function after you get this data back.

Hopefully, this pattern is starting to become comfortable!

If you want a real example, I am building www.everyhour.xyz and you can see the service worker in action, in the dev tools.

A great video that taught me a lot — and also shows how to interact with IndexedDB at the service worker and app level:

Founder of EveryHour.xyz and Product Owner @ dunnhumby; just genuinely interested in a lot of things. Built racecars, built electronics, now building software

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store