Working with IndexedDB with Raw JS and localForage
IndexedDB
IndexedDB is a large-scale, NoSQL storage system.IndexedDB is more power than local storage and its useable to store a huge amounts of data. IndexedDB Data storage limits are usually quite large. There are many applications that used it as offline storage.
IndexedDB components
1. Database : Database is collection of data set. It optimized data to search as fast as possible.
2. Object Store: An Object Store stores data like a table in a relational database.
3. Index: The index is the primary key that will be unique through which information can be easily retrieved.For example, if we are storing some book lists, we might want to fetch them later by their name, price,and author name.
4. Transaction: The transaction method returns immediately a transaction object.
5. Cursor: Iterate multiple data form object store
Check browser supportable or not
There is a simple way to check whether indexedDB is supportable or not in the user browser.
<code class="language-javascript"> if (window.indexedDB) { console.log("IndexedDB is supportable for this browser"); } </code>
Create Database and objectStore
`Note: objectStore is a bucket to store data like to similar tables in traditional relational databases`
<code class="language-javascript"> const request = window.indexedDB.open("testdb", 1); // if database created successfully request.onsuccess = (e) => { let database = e.target.result; console.log(`successfully called ${database.name} database and version is ${database.version}`); }; // get any error of create database request.error = (e) => { console.log(`error: ${e.target.error}`); }; /* create a new database or increase the version number of an existing database onupgradeneeded event create the object stores needed for this version of the database */ request.onupgradeneeded = (e) => { db = e.target.result; // create object store db.createObjectStore(["products"], { keyPath: "title" }); }; </code>
add data in storeObject
`Note: transaction is a method to access object store `
<code class="language-javascript"> setTimeout(() => { const items = { title: "cat_products", data: [ { name: "product-1", price: 10, }, { name: "product-2", price: 15, }, { name: "product-3", price: 20, }, { name: "product-4", price: 25, }, ], }; db.transaction("products", "readwrite") .objectStore("products") .add(items); console.log("product added"); }, 1000); </code>
get data in storeObject
<code class="language-javascript"> const dbTransaction = db.transaction("products", "readonly") .objectStore("products") .get("cat_products"); dbTransaction.onsuccess = (e) => { console.log(e.target.result); }; </code>
delete index in storeObject
<code class="language-javascript"> db.transaction("products", "readwrite") .objectStore("products") .delete("cat_products"); </code>
There are also a variety of packages to make it easier to manage indexed DB operations such as LocalForage,idb etc. LocalForage is a popular package that is used on twitter. I am using it in a project which can easily manage the operation of IndexedDB.
Some operations through LocalForage
Set data with LocalForage
<code class="language-javascript"> import localForage from "localforage" localForage .setItem("books", [ {name: 'Life's Amazing Secrets', author: 'Gaur Gopal Das'}, {name: 'The Art of Thinking Clearly',author: 'Rolf Dobelli'} ]); </code>
get data with LocalForage
<code class="language-javascript"> localForage.getItem("books") .then(response => { console.log(response) }) </code>
remove item with LocalForage
<code class="language-javascript"> localForage.removeItem('books') .then(function() { console.log('Key is cleared!'); }) </code>
clear data with LocalForage
<code class="language-javascript"> localForage .clear() .then(function() { console.log('Database is now empty.'); }) </code>