prevent calling /shopping_carts api multiple times in jamtracks listing

This commit is contained in:
Nuwan 2024-12-22 21:59:28 +05:30
parent 48547d2cb1
commit 61eddbb2bc
1 changed files with 53 additions and 9 deletions

View File

@ -1,5 +1,5 @@
import { getShoppingCart, addJamtrackToShoppingCart, removeShoppingCart } from "../helpers/rest"
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useCallback } from "react";
export const useShoppingCart = () => {
const [loading, setLoading] = useState(false);
@ -19,7 +19,21 @@ export const useShoppingCart = () => {
const getCartItems = async () => {
// const getCartItems = async () => {
// try {
// setLoading(true);
// const resp = await getShoppingCart();
// const data = await resp.json();
// setShoppingCart(data);
// } catch (error) {
// console.log(error);
// setError(error);
// }finally{
// setLoading(false);
// }
// }
const getCartItems = useCallback(async () => {
try {
setLoading(true);
const resp = await getShoppingCart();
@ -31,9 +45,21 @@ export const useShoppingCart = () => {
}finally{
setLoading(false);
}
}
}, []);
const addCartItem = async (options) => {
// const addCartItem = async (options) => {
// try {
// const resp = await addJamtrackToShoppingCart(options);
// const data = await resp.json();
// setShoppingCart([...shoppingCart, data]);
// return data;
// } catch (error) {
// console.log(error);
// return false;
// }
// }
const addCartItem = useCallback(async (options) => {
try {
const resp = await addJamtrackToShoppingCart(options);
const data = await resp.json();
@ -43,9 +69,21 @@ export const useShoppingCart = () => {
console.log(error);
return false;
}
}
}, [shoppingCart]);
const removeCartItem = async (id) => {
// const removeCartItem = async (id) => {
// try {
// await removeShoppingCart({id});
// setShoppingCart(shoppingCart.filter(item => item.id !== id));
// return true;
// } catch (error) {
// console.log(error);
// return false;
// }
// }
const removeCartItem = useCallback(async (id) => {
try {
await removeShoppingCart({id});
setShoppingCart(shoppingCart.filter(item => item.id !== id));
@ -55,11 +93,17 @@ export const useShoppingCart = () => {
return false;
}
}
}, []);
const hasOnlyFreeItemsInShoppingCart = () => {
// const hasOnlyFreeItemsInShoppingCart = () => {
// return shoppingCart.length === 0 || shoppingCart.every(item => item.product_info.free);
// }
const hasOnlyFreeItemsInShoppingCart = useCallback(() => {
return shoppingCart.length === 0 || shoppingCart.every(item => item.product_info.free);
}
}, [shoppingCart]);
return{
shoppingCart, error, loading, removeCartItem, addCartItem, cartTotal, hasOnlyFreeItemsInShoppingCart