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

ACGoff
2 min readMay 10, 2021

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…

--

--

No responses yet