diff options
| author | Rafi Zadanly <rafizadanly@gmail.com> | 2022-12-14 12:01:13 +0700 |
|---|---|---|
| committer | Rafi Zadanly <rafizadanly@gmail.com> | 2022-12-14 12:01:13 +0700 |
| commit | 39a2e8012ba38d6663820ae27080a2b843c08c5f (patch) | |
| tree | bdc299534531bd104e0795c1389c97f187c8cdd1 /src/helpers | |
| parent | 62e4264a9d5c1834e2137e33b62e5618017de1d0 (diff) | |
Add to cart to localstorage
Diffstat (limited to 'src/helpers')
| -rw-r--r-- | src/helpers/cart.js | 54 |
1 files changed, 54 insertions, 0 deletions
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 |
