From 39a2e8012ba38d6663820ae27080a2b843c08c5f Mon Sep 17 00:00:00 2001 From: Rafi Zadanly Date: Wed, 14 Dec 2022 12:01:13 +0700 Subject: Add to cart to localstorage --- src/helpers/cart.js | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/helpers/cart.js (limited to 'src/helpers') diff --git a/src/helpers/cart.js b/src/helpers/cart.js new file mode 100644 index 00000000..07e47324 --- /dev/null +++ b/src/helpers/cart.js @@ -0,0 +1,54 @@ +const getCart = () => { + const cart = localStorage.getItem('cart'); + if (cart) return JSON.parse(cart); + return []; +} + +const setCart = (cart) => { + localStorage.setItem('cart', JSON.stringify(cart)); + return true; +} + +const getItemIndex = (product_id) => { + const cart = getCart(); + return cart.findIndex((item) => item.product_id == product_id); +} + +const addToCart = (product_id, quantity) => { + let cart = getCart(); + let itemIndexByProductId = getItemIndex(product_id); + if (itemIndexByProductId > -1) { + updateItemCart(product_id, quantity); + } else { + cart.push({ product_id, quantity }); + } + setCart(cart); + return true; +} + +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; + } + setCart(cart); + return true; +} + +export { + getCart, + addToCart, + deleteItemCart, + updateItemCart +} \ No newline at end of file -- cgit v1.2.3