diff options
| author | Rafi Zadanly <rafizadanly@gmail.com> | 2022-12-14 17:48:03 +0700 |
|---|---|---|
| committer | Rafi Zadanly <rafizadanly@gmail.com> | 2022-12-14 17:48:03 +0700 |
| commit | bd4008ac5c2a22c1d99239ba0691cfb8ef0e9aea (patch) | |
| tree | c2f1289cfaa68ba5154e695f26d80278f42208f1 /src/helpers | |
| parent | 4e2b85a16b032df07686fd044ba9183afceb8b11 (diff) | |
add to cart, cart page, change cart item quantity
Diffstat (limited to 'src/helpers')
| -rw-r--r-- | src/helpers/cart.js | 39 |
1 files changed, 13 insertions, 26 deletions
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 |
