#BLOG4 Meet IndexedDB, which stores your data locally in a browser
You read it right!
IndexedDB can store your data easily in any browser and you can test it using the console option.
But let us first understand what is IndexedDB.
GitHub: https://github.com/jay1299/IndexedDB
What is IndexedDB?
It is a NoSQL data storage solution API for client-side storage. It can store structured data and blobs. Apart from storing data on the user’s browser, you can even run queries on your stored data using transactions. You can use get() and put() method types to perform operations like inserting, updating, and retrieving the data.
There are various other NoSQL data storage solutions available in the market such as MongoDB, CouchDB, DynamoDB, etc. You can see its comparison in the below Google’s Bard generated table.
IndexedDB is a bit complex to use since it requires setting up the code and then querying on that code consumes much time whereas the other NoSQL databases are much easier to set up.
In this blog, I will show you an example of how to save and retrieve data from an IndexedDB data storage.
Project:
In this demo, I am creating a simple movie database that stores the movie name, the director’s name, and its Genre. All the entries have a unique ID.
The above line will check the compatibility of the browser to check whether it supports IndexedDB.
The open() method is used to initiate a connection by calling either an onsuccess event or onerror event. These events are triggered according to the results of the open() method which takes 2 arguments.
Database name
Version number
The database name in our project is “Database1“ and the version number is used to specify the version of our database. If the user is trying to create a new version then he can specify it as 2, 3, 4… according to the version he is using.
In the above image, you can see the onerror event which will throw an error when any of the below issues occur:
The browser is not compatible with IndexedDB.
You are calling a method that is never instantiated or a typo when calling the method.
Wrong syntax for running a query.
And other scenarios when you try modifying the code.
You can see the correct output or an error using the below path:
Right click → Inspect → Console
In this step, we would be creating the structure/schema of the database. The ‘onupgradeneeded’ event is triggered by the open() method when your database does not exist already which is true in our case.
In this event, you can specify your attributes/columns for the database and those are created using the ‘createIndex’ method.
The ‘request’ constant created above is used to call the required methods such as createIndex, and createObjectStore.
object stores: A database typically contains one or more object stores. Object stores can be thought of as similar to tables in SQL databases and should contain objects of the same type (not JavaScript data type). For example, for a site persisting user profiles and notes, you can imagine a
people
object store containingperson
objects, and anotes
object store. A well structured IndexedDB database should have one object store for each type of data that needs to be persisted.
using const db we created the below 2 indexes:
Movie_Details: a compound index that has 2 attributes, Name, and Director. This will store the name of the movie and its director.
Movie_Genre: an index to store the genre of the above-mentioned movie such as horror, rom-com, sci-fi, etc.
The above indexes are stored in an objectstore named “Movie” having a keypath “ID“. A key path is a property that always exists and contains a unique value. Consider it as a primary key of our database.
If you remember the open() method outputs which was onerror and onsuccess, well this is the 2nd output that will run when there is no halt in steps till now.
In this step, we define the onsuccess event processing steps which will be inserting data into our database using the same constant ‘db’ from the 2nd step.
We use the transaction() method to perform operations on our data with readwrite mode since we would be inserting data as well in the database and not just reading it.
transaction: A transaction can be thought of as a safe wrapper around an operation or group of operations. If one of the actions within a transaction fails, all of the actions are rolled back. Transactions are specific to one or more object stores, which you define when you open the transaction. They can be read-only or read and write. This signifies whether the operations inside the transaction read the data or make a change to the database.
then we create the references of all the indexes and these references are called using the const “Main” which refers to the object store.
CompoundIndex: Refers to the index Movie_Details
GenreIndex: Refers to the index Movie_Genre
The put() method is used to insert data into our database. The syntax and the way I have inserted the data are pretty obvious from the above image.
Now comes the crux of this project, which is data retrieval! 🏁
get() method is used to retrieve our stored data from the database. This method has different forms such as getAll() to retrieve all the matching data.
Query 1: I am using constant GetallQuery using the getAll() method which will retrieve all the details of the movie having the genre as “Rom-Com”.
Query 2: I am using the get() method to retrieve details attached to the ID “103”.
Query 3: I am using CompoundQuery to get details of the movies having the movie name “Evil Dead” and the Director is “Alex Marshal”.
I have added three onsuccess functions which are triggered when the above three created query constants are executed successfully. These functions will log the output in the console tab of the browser and in the end using the onComplete event, we close the connection!
The output:
Right click → Inspect → Console
You can run an ad or news in our newsletters which gets you ahead by decluttering your product/article/project/innovation in tech and bringing your expected audience closer to you.