summaryrefslogtreecommitdiff
path: root/src/helpers
diff options
context:
space:
mode:
authorRafi Zadanly <rafizadanly@gmail.com>2022-12-14 12:01:13 +0700
committerRafi Zadanly <rafizadanly@gmail.com>2022-12-14 12:01:13 +0700
commit39a2e8012ba38d6663820ae27080a2b843c08c5f (patch)
treebdc299534531bd104e0795c1389c97f187c8cdd1 /src/helpers
parent62e4264a9d5c1834e2137e33b62e5618017de1d0 (diff)
Add to cart to localstorage
Diffstat (limited to 'src/helpers')
-rw-r--r--src/helpers/cart.js54
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