Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and retrieve Shopping Cart items in localstorage?

I'm creating a shopping cart for an e-commerce website and want to store the products in the browser localstorage.

I've implemented the following functions into my code for adding and retrieving products

addToCart() is the function that launches each time the Add to Cart button is pressed.
addProduct() adds each product to the cartList.
getProductsFromLocalStorage() retrieves the products from the localStorage and adds the products to the cartList.

  function addToCart(trigger) {
    var cartIsEmpty = cartWrapper.hasClass('empty');
    //get localstorage cart product list
    getProductsFromLocalStorage();
    //update cart product list
    addProduct();
    //update number of items
    updateCartCount(cartIsEmpty);
    //update total price
    updateCartTotal(trigger.data('price'), true);
    //show cart
    cartWrapper.removeClass('empty');
  }

  function addProduct() {

    productId = productId + 1;
    var productName = document.getElementById('reebok').innerHTML;
    var productPrice = document.getElementById('p_price').getAttribute('data- value');
    var image = document.getElementById("main_img").src;
    var productSize = document.getElementById('size').value;
    var productColor = document.getElementById('color').value;
    value = parseFloat(productPrice).toFixed(2);

    var productAdded = $('<li class="product"><div class="product-image"><a href="#0"><img src="'+ image +'" alt="placeholder"></a></div><div class="product-details"><h3><a href="#0">' + productName + '</a></h3><span class="price">'+ productPrice +'</span><div class="actions"><a href="#0" class="delete-item">Delete</a><a class="delete-item">'+ productSize +'</a><a class="delete-item">'+ productColor +'</a><div class="quantity"><label for="cd-product-' + productId + '">Qty</label><span class="select"><select id="cd-product-' + productId + '" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');

    cartList.append(productAdded);

    let products = [{'productId' : productId + 1, image : image, name : productName, price: productPrice, size: productSize, color: productColor}];

    localStorage.setItem('products', JSON.stringify(products));

  }

  function getProductsFromLocalStorage() {
    const cs = localStorage.getItem('products');
    if (cs === null) {
      addProduct();
    } else {
      $.each(cs.products, function(key, value) {
        cartList.prepend($('<li class="product"><div class="product-image"><a href="#0"><img src="'+ value.image +'" alt="placeholder"></a></div><div class="product-details"><h3><a href="#0">' + value.name + '</a></h3><span class="price">${value.price}</span><div class="actions"><a href="#0" class="delete-item">Delete</a><a class="delete-item">' + value.size + '</a><a class="delete-item">' + value.color + '</a><div class="quantity"><label for="cd-product-' + value.productId + '">Qty</label><span class="select"><select id="cd-product-' + value.productId + '" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>'));
      });
    }
  }

I've now got the issue of not being able to retrieve the cart items from the local storage and add them to the cart with new items. This means the shopping cart items are saved in storage but I see a blank cart when I attempt to add new items as below:

Screenshot of Shopping Cart

The demo of this code is at https://codyhouse.co/demo/add-to-cart-interaction/index.html.

Thanks for any assistance,

James.

like image 802
JamesM00 Avatar asked Mar 24 '19 21:03

JamesM00


People also ask

Can localStorage store objects?

Local storage can only save strings, so storing objects requires that they be turned into strings using JSON. stringify - you can't ask local storage to store an object directly because it'll store “[object Object]”, which isn't right at all! That also means the object must be run through JSON.

Can we store blob in localStorage?

You can store Blobs in LocalStorage as base64 strings, which is really inefficient. Plus, many LocalStorage implementations only let you store up to 5MB, so you hit the limit pretty fast.


1 Answers

You should use browser's localstorage for it.

In your function addProduct, you should add array of products to a local storage item say products; like so:

function addProduct(){
    let products = [];
    if(localStorage.getItem('products')){
        products = JSON.parse(localStorage.getItem('products'));
    }
    products.push({'productId' : productId + 1, image : '<imageLink>'});
    localStorage.setItem('products', JSON.stringify(products));
}

If you want to remove product, you can do it like so:

function removeProduct(productId){

    // Your logic for your app.

    // strore products in local storage

    let storageProducts = JSON.parse(localStorage.getItem('products'));
    let products = storageProducts.filter(product => product.productId !== productId );
    localStorage.setItem('products', JSON.stringify(products));
}

Please check this fiddle for working demo.

like image 58
Vinit Divekar Avatar answered Oct 12 '22 23:10

Vinit Divekar