IndexedDB with promises and async/await
Every once in a while we need to store/persist something in a database or we need to cache some data. It can be because we want to improve performance, support offline mode or we just need feature that need web storage.
So, what are the options that we have right now:
1) Store all data on server database (SQL or NoSQL)
2) LocalStorage / SessionStorage - limited memory (around 5MB)
3) WebSQL - it has been deprecated in favor of IndexedDB
4) IndexedDB - designed as “one true” browser database with 50MB and more
tl;dr Use some library from conclusion section to make your life easier.
So IndexedDB FTW
Just to name few of main concepts in IndexedDB:
database, objectStore, indexes, transaction, cursor, …
Show me the code
Let’s write code to put some data into database.
Now let’s make our life easier
For this purpose I’m going to use idb written by Jake Archibald. Together with idb library, we can use new async/await feature of browsers.
Oh wait, but async/await is not supported by all browsers. No problem, take your code, transpile it with babel/traceur/typescript and we are good to go.
Now let’s take a look how we can write storing data in better way.
😎😎😎
Although IndexedDB has asynchronous API, this looks so pretty, doesn’t it?
Now, just to verify that data is stored, open devtools application tab.
We can get data by specific key or we can get all stored data with code below.
Conclusion
One benefit of web storage like this is when we are using Redux or some sort of state management, if we save users state into IndexedDB and when next time user visits our page/application, user get previously saved state and boom, user can continue where he/she left.
There is lot of libraries out there to make our life easier when working with IndexedDB. Just to name a few: localForage, pouchdb, idb, idb-keyval, Dexie.js, IDBWrapper