How to save products in the browsers local storage
Updated: 14-Mar-2022 / Tags: Javascript and Local Storage / Views: 3974 - Author: George
Introduction
Hello everyone, in this article we are going to see basic shopping cart actions like storing, updating, and deleting products with javascript using the browser's local storage.
Storing data in the browser's local storage (actually we storing the data in our hard drive) our applications will work faster and the user will enjoy a good experience. The only thing that you never do is, storing passwords in local storage. That is not a good idea.
To begin let me quick describe the tutorial's process. We have a JSON file where our products are stored. The file's name is products.json. We are gonna grab the products from the JSON file with javascript and we will put them in the browser's local storage.
Now that we have the products in the local storage we are going to target some of them and put them in
a shopping cart, and we will store the cart also in the local storage.
Let's start.
Files we need
- We need a products.json JSON file with the stored products. If you want to follow along you can copy the file's content here.
- We need an index.html file, only to put the script tags so we can run the javascript file in the browser.
- And we need a script.js javascript file to write our code.
The JSON file
This is our products.json file. Every product is an object and has properties.
In our case here every product has an id, which must be unique, an image , a name, a price,
and a quantity property.
I display here just one product so you can have a visual of our json file and what's in it.
[
{
"id": 1,
"image": "bike-1.jpeg",
"name": "Orient Vita Pro 28",
"price": "284.50",
"quantity": 1
},
// more products are following
The index file
In the index.html file we include the script tags with the src attribute set to the name of our javascript file.
<body>
<script src="script.js"></script> <!-- Link to the javascript file -->
</body>
The javascript file
The first thing we do in the script.js file, is to fetch the products from
the json file and store them in the local storage, and also if there isn't a cart item in the local storage
we initialize an empty one.
Let's start.
We are going to use the fetch() method in line 1. This is a simple AJAX GET
request, so the only thing that we have to do is to pass in the method, as an argument, the path to our json file
which is "products.json".
We know that the fetch method returns a promise and that we have to resolve that promise with the .then() method, that means that we have to chain the .then() method to the fetch() method.
fetch("products.json")
.then(function(response){
return response.json();
})
.then(function(data){
localStorage.setItem("products", JSON.stringify(data));
if(!localStorage.getItem("cart")){
localStorage.setItem("cart", "[]");
}
});
-
In line 2 we chain as we said above the .then() method which takes a function as an argument.
We pass a variable in the function as an argument, usually we called it "response".
The promise that the fetch() method returns, resolves to a Response object, which is stored in the response variable. -
Now in line 3 we use the .json() method of the Response object, to parse the response body text as json. Also we have to return the parsed json data.
return response.json();
-
The .then() method returns also a Promise. So in line 5 we use another .then() method to resolve the json response to the data variable.
.then(function(data){
-
Now the data variable is holding the products from the json file, now we can put them in the local storage. In line 6 we are calling the local storage object and we use the .setItem() method. The setItem() method takes two arguments, the first argument is the key, and the second the value. The data in the localstorage are stored as key => value pairs.
localStorage.setItem("products", JSON.stringify(data));
In our case here we set the key to "products" and the value to the JSON data (products). But because we can only store string type values in the local storage we have to use the JSON.stringify() method to convert them to a string.
-
In line 7-9 we have an if block and we are checking if there is a "cart" key in the local storage.
if(!localStorage.getItem("cart")){ localStorage.setItem("cart", "[]"); }
We use the .getItem() method to fetch the "cart" key. If the getItem("cart") returns null, that means that the "cart" key doesn't exists in the local storage. If that happens we create the "cart" key and we set the value to an empty array in line 8.
-
Now when we run the code we will store the products to the local storage and we will also create an empty cart list. In the image bellow we see the products stored in the local storage and the empty cart array.
To see the local storage in the browser: Open Dev Tools go to > Application and on the left sidebar select Local Storage.
Adding products to the cart
Now that we have our products in the local storage let's see how we can target them and put them in the cart list.
We are gonna first set some global variables so we don't repeat our self.
// SETTING GLOBAL VARIABLES SO WE CAN ACCESS THEM FROM INSIDE THE FUNCTIONS.
let products = JSON.parse(localStorage.getItem("products"));
let cart = JSON.parse(localStorage.getItem("cart"));
- In line 15 we creating a variable named products, and we store in that variable all products from the local storage. Noticed that we have to convert the data to objects with the JSON.parse() method so we can work with them.
- The same thing we do on line 16 with the cart list.
Adding items to the cart
We are going to write a function to adding the products in the cart item list.
The function takes as an argument the id of the product we want to put in the cart.
Let's say that our products are displayed in a page and when the user click's on the add to cart button
the ddItemToCart() function runs.
function addItemToCart(productId){
let product = products.find(function(item){
return item.id == productId;
});
if(cart.length == 0){
cart.push(product);
}else{
let res = cart.find(element => element.id == productId);
if(res === undefined){
cart.push(product);
}
}
localStorage.setItem("cart", JSON.stringify(cart));
}
addItemToCart(1); // adding the product with id=1 to the cart.
- In line 19-21 we go through the products with the find() method and we search for a product with the same id as our argument. If there is a match, the find() method will return the matched product and will store it in the let product variable.
- Next in line 23 we starting an if statement. The logic here is that we want to check if the product already exists in the cart list. If the product exists in the cart we won't add it again.
-
First we check if the cart list has stored products by checking the length property. If the length is equal to zero, then the cart is empty. Inside the if statement we are using the .push() method to insert the product to the cart array.
if(cart.length == 0){ cart.push(product); }
-
If there are products already stored in the cart list, then we search again with the find() method, line 26, to see if the incoming product id exists inside the cart list. If the find() method returns undefined, that means that the product that we want to add is not in the cart. And in line 28 we safely can add the product to the cart. With this logic we avoid any duplicate products in the cart.
else{ let res = cart.find(item => item.id == productId); if(res === undefined){ cart.push(product); } }
-
Now that we have added the product in the cart list, we will put the cart back in the local storage. Line 31.
localStorage.setItem("cart", JSON.stringify(cart));
-
And in line 33 we run the function and we adding the product with id=1 to the cart.
addItemToCart(1); // run the function and add the product with id=1 to the cart.
-
As you can see in the image the product is added to the cart list inside the local storage.
Removing items from the cart
Now let's see how we can remove a product from the cart. Let's say we want to remove the product that we have added earlier. We are going to write again a function, which function takes as an argument the id of the product we want to remove.
Let's imagine that we have a shopping cart in our page and we are displaying the items added to the cart. And there is a Remove item button, which when we click on it the removeItemFromCart(id) function runs.
function removeItemFromCart(productId){
let tempCart = cart.filter(item => item.id != productId);
localStorage.setItem("cart", JSON.stringify(tempCart));
}
removeItemFromCart(1);
- To remove the product from the cart array we have to create a new array with all the products in it, except the product we want to remove. That is what we are doing in line 39. We run the filter() method against our cart list, which filter() method will return an array where the product with the given id is not included.
- Now that what we have to do is to take the new array tempCart and put it in the local storage. Line 42. The data in the local storage will be overridden with the new one, without the removed product.
- If we run the function, in line 42, we will see the item with id=1 is removed from the cart.
Updating the quantity of a product
To update the quantity of a product we will write once again a function, but this time the function accepts two arguments. With the first argument we are telling the function which product we want to update (product id), and with the second we set the new quantity value.
function updateQuantity(productId, quantity){
for(let product of cart){
if(product.id == productId){
product.quantity = quantity;
}
}
localStorage.setItem("cart", JSON.stringify(cart));
}
updateQuantity(1, 8);
- The logic here is simple, we loop through the cart items in line 46.
- We search for the product we want to update base on the given id. Line 47.
- And if the condition is true, we target the products quantity and we set the new value, in line 48.
- In line 51 we store the updated cart back to the local storage. And we always .stringify() the data.
- And last in line 53, we run the function, and we want to update the product with id=1, and set the quantity to eight.
-
The local storage will look something like that. We can see that the quantity is updated to eight.
Summary
In this tutorial we saw how to add, update and remove products from the local storage with JavaScript.
Last Words
I hope you found the article useful, and you enjoyed reading it.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 668