Search code examples
angulartypescriptangular7cartshopping-cart

How to store multiple Json object data in local storage & if existing how to update it


In my angular project have a shopping cart feature. Soi wants some help from anyone.

1. How to check that user previously adds to cart (by matching existing product ID in Local storage with new selected product ID), now selected product.

2. If add previously to cart, how to update it(new Quantity or new Type to under existing product ID).

3. If did not add previously, how to push to local storage as a new product under new Product ID. Can't to be effect other selected cart product

Angular 7 cli

Product.components.ts

constructor(private cartService:CartServicesService)

public addToCart(productId : any , productTypeStatus:any , quantityCount:any ){ 

var cartProductData = { 
  "productId": productId,
  "productSelectedTypeId": productTypeStatus,
  "productQuantity": quantityCount
};  

this.cartService.addToCart(cartProductData); //send data to cart-service.ts

}

Cart-services.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CartServicesService {

constructor() { }

public addToCart(cartData:any) {

 console.log(cartData);

 //save data in local storage------------------------------------
 localStorage.setItem('cartObject', JSON.stringify(cartData)); 

 }
}

In local storage

Key   : cartObject
Value : {"productId":3,"productSelectedTypeId":null,"productQuantity":4}

Solution

  • Well, the steps you have mentioned on your question, are generally correct. However, I would recommend you to store it as an array of objects, instead of just an object on its own.

    This is how you can get the cart data from your localStorage.

    let cart =  JSON.parse(localStorage.getItem('cartObject'));
    

    Then, we use Array.some() to check if the new item on your shopping list exists on the cart from cartObject.

    let isInCart = false;
    if (cart) {
      isInCart = cart.some(item => item.productId === 
    cartProductData.productId));
    } else {
      cart = [];
    }
    

    Then, we handle it based on isInCart, which is a boolean value that denotes if the item exists on the cart:

    if (isInCart) {
      cart.map(item => {
        if (item.productId === cartProductData.productId) {
          item.productQuantity += cartProductData.productQuantity;
        }
        return item;
      });
    } else {
      cart.push(cartProductData);
    }
    

    Then, we store the updated cart on your localStorage:

    localStorage.setItem('cartObject', JSON.stringify(cart));