DEV Community

Cover image for Local Storage for shopping cart in Javascript
Hamid Haghdoost
Hamid Haghdoost

Posted on • Updated on

Local Storage for shopping cart in Javascript

In previous exercise class with students, we created a simple shopping cart with JS. Today I had another lecture and I added localStorage feature to this project and in this version of project the added items could be persist in cart with refresh and we added another file named cart.html that shows added cart items. You can see source code of this project in v2.0.0 tag in this repo: JsShoppingCart
In this lecture we used JS Objects to store cart items like this:

if (id in cart) {
} else {
    let cartItem = {
        title: title,
        price: price,
        qty: 1
    cart[id] = cartItem
Enter fullscreen mode Exit fullscreen mode

and we added cart items to localStorage like this:

localStorage.setItem("cart", JSON.stringify(cart));
Enter fullscreen mode Exit fullscreen mode

And finally in the cart.js file we can create table rows like this:

let cart = {};
if (localStorage.getItem("cart")) {
    cart = JSON.parse(localStorage.getItem("cart"));

let tbody = document.getElementById("tbody");

for (let id in cart) {
    let item = cart[id];

    let tr = document.createElement('tr')

    let title_td = document.createElement('td')
    title_td.textContent = item.title

    let price_td = document.createElement("td");
    price_td.textContent = item.price;

    let qty_td = document.createElement("td");
    qty_td.textContent = item.qty;


Enter fullscreen mode Exit fullscreen mode

In the next session we want to talk about AJAX and we will get the product from an API. If you find this code useful, give it a like :)

Top comments (0)