From bd4008ac5c2a22c1d99239ba0691cfb8ef0e9aea Mon Sep 17 00:00:00 2001 From: Rafi Zadanly Date: Wed, 14 Dec 2022 17:48:03 +0700 Subject: add to cart, cart page, change cart item quantity --- src/helpers/cart.js | 39 +++++++++++++-------------------------- 1 file changed, 13 insertions(+), 26 deletions(-) (limited to 'src/helpers') diff --git a/src/helpers/cart.js b/src/helpers/cart.js index 07e47324..8712c03a 100644 --- a/src/helpers/cart.js +++ b/src/helpers/cart.js @@ -1,7 +1,7 @@ const getCart = () => { const cart = localStorage.getItem('cart'); if (cart) return JSON.parse(cart); - return []; + return {}; } const setCart = (cart) => { @@ -9,18 +9,18 @@ const setCart = (cart) => { return true; } -const getItemIndex = (product_id) => { - const cart = getCart(); - return cart.findIndex((item) => item.product_id == product_id); +const getItemCart = (product_id) => { + let cart = getCart(); + return cart[product_id]; } -const addToCart = (product_id, quantity) => { +const createOrUpdateItemCart = (product_id, quantity) => { let cart = getCart(); - let itemIndexByProductId = getItemIndex(product_id); - if (itemIndexByProductId > -1) { - updateItemCart(product_id, quantity); + let isFoundInCart = cart[product_id]; + if (isFoundInCart) { + cart[product_id].quantity = quantity; } else { - cart.push({ product_id, quantity }); + cart[product_id] = { product_id, quantity }; } setCart(cart); return true; @@ -28,27 +28,14 @@ const addToCart = (product_id, quantity) => { const deleteItemCart = (product_id) => { let cart = getCart(); - let itemIndexByProductId = getItemIndex(product_id); - if (itemIndexByProductId > -1) { - cart.splice(itemIndexByProductId, 1) - } - setCart(cart); - return true; -} - -const updateItemCart = (product_id, quantity) => { - let cart = getCart(); - let itemIndexByProductId = getItemIndex(product_id); - if (itemIndexByProductId > -1) { - cart[itemIndexByProductId].quantity += quantity; - } + delete cart[product_id] setCart(cart); return true; } export { getCart, - addToCart, - deleteItemCart, - updateItemCart + getItemCart, + createOrUpdateItemCart, + deleteItemCart } \ No newline at end of file -- cgit v1.2.3