Next step to client-side storage
In my past one blog, I wrote about how I improve the performance of the application using the local storage. And the problem local storage solves.
But now I face another problem about the client storage. My project is simply about order management software for the rental clothing industry.
In the rental clothing industry, Showrooms or small shops have a big problem. The problem starts when one order has a single or multiple items that are booked in a particular time range.
Now, a second order wants the same item in between that particular time range. If, by mistake, the second order books that item, then the problem starts.
The item is booked two times in that particular time range. That is called double booking of the item.
This mistake is created by the use of traditional register booking. Now, when I need to store the items data, that is a small amount of data, so I simply use the local storage.
But now I need another and a big storage for storing order details. I build two features: first one is for showing all the orders and second one is for showing the full order.
To implement those features and to maintain the user experience, I decide to store a small amount of data about the order on the client side. First, I decide to store data in local storage.
But to store data in the local storage is not a good option because the local storage is used for storing small details about the application, and storing order details in the local storage compromises the performance of the application.
Now I want a new storage option for storing order details. And again I find out, and that is the IndexedDB.
To integrate IndexedDB in my application, I want to learn about that storage. I search multiple videos about IndexedDB, but no one is teaching me properly.
After finding hundreds of tutorials, I finally found one tutorial that is teaching properly how to integrate IndexedDB in the application. Now I want to share that learning with you.
To integrate IndexedDB, we want to create first one database in IndexedDB. The dbConnect is built for that and used to get the reference of the created database.
To build that function, we want to create first two environment variables: db_name and version. Those two variables describe the name and the version of that database.
If any updation happens in the version variable, then this function will execute and update the database.
const dbConnect = () => {
const req = indexedDB.open(db_name, version);
req.onupgradeneeded = () => {
const db = req.result;
// Access the reference of the database.
const payload = {
keyPath: "id",
autoIncrement: true
};
// The payload is for creating a primary key.
db.createObjectStore("orders", payload);
// Create the object that is called store in IndexedDB.
};
req.onsuccess = () => {
console.log("Success", req.result);
};
req.onerror = () => {
console.log("Failed", req.error);
};
};
Now, in the function, we create first one database and get the reference of that database. The req.onupgradeneeded is an event for updating the database when the version variable is changed, then this event is run and updates the database.
The req variable sends the request to open the database, and after the request is complete, we now have access to the database connection reference. The payload is the rule for how the primary key of that particular store will be generated.
To create a store, first we access the result object, and in the result object, we use the createObjectStore method. onsuccess and onerror are events that indicate the success or failure of the connection.
The function dbConnect is an asynchronous function, so the next step is to convert this asynchronous function to a synchronous function. To create a synchronous function, we simply wrap this function into the promise.
Let's do that.
We do this promise in the req.onsuccess or req.onerror event. If the req is successful, we resolve the promise; otherwise, we reject the promise.
The updated event is:
req.onsuccess = resolve();
req.onerror = reject();
const dbConnect = () => {
return new Promise((resolve, reject) => {
const req = indexedDB.open(db_name, version);
req.onupgradeneeded = () => {
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
};
Now our function is converted into the synchronous function. Now, the next step we explore is how to store, update, read and delete the data.
In IndexedDB, all the operations are transactions. Means if any error happens, then all the started operations are undone.
Now the next step is to get knowledge about the permission. When we want to store or delete or update the data, the first step is to define the permission.
readonly, readwrite are the types of permission.
const storeData = async () => {
try {
const db = await dbConnect();
const transaction = db.transaction("orders", "readwrite");
// Define the permission.
const payload = {
name: "Neel",
email: "neel@gmail.com"
};
// The data to store.
transaction.objectStore("orders").add(payload);
transaction.oncomplete = () => {
console.log("Data Stored Successfully.");
};
} catch (error) {
console.log(error);
}
};
This is all about storing the data. Now we learn about reading the data.
For reading the data, we use readonly permission. The getAll() function is used to get all the data, and get() is used to get particular data.
const readData = async () => {
try {
const db = await dbConnect();
const transaction = db.transaction("orders", "readonly");
// Define the permission.
const request = transaction.objectStore("orders").getAll();
request.onsuccess = () => {
console.log("Data Fetched Successfully.", request.result);
};
} catch (error) {
console.log(error);
}
};
This is all about how to read the data. Now next, we learn how to update the data.
To update the data, we use the readwrite permission.
const updateData = async () => {
try {
const db = await dbConnect();
const transaction = db.transaction("orders", "readwrite");
// Define the permission.
const store = transaction.objectStore("orders");
// In this store we do not use any function; either we get the reference.
const req = store.get(id); // Get old data.
req.onsuccess = () => {
const data = req.result;
if (!data) return;
const payload = {
...data,
name: "Jay",
email: "Jay@gmail.com"
};
// Only change name and email and other data store as it is.
store.put(payload);
};
} catch (error) {
console.log(error);
}
};
This is all about how to update the data. Now next, we learn how to delete the data.
To delete the data, we use the .delete() method.
const deleteData = async () => {
try {
const db = await dbConnect();
const transaction = db.transaction("orders", "readwrite");
// Define the permission.
const store = transaction.objectStore("orders");
// In this store we do not use any function; either we get the reference.
const req = store.delete(id); // Delete data.
} catch (error) {
console.log(error);
}
};
Now we successfully implemented the IndexedDB in our project.
If I made any mistake, then share my mistake in the comments.
Top comments (0)