type CartProduct = Product & { quantity: number; }; type CartState = { cartItems:…
- User
type CartProduct = Product & { quantity: number; };
type CartState = { cartItems: CartProduct[]; addItemToCart: (item: Product) => void; increaseQuantity: (productId: number) => void; decreaseQuantity: (productId: number) => void; };
const useCartStore = create((set, get) => ({ cartItems: [],
addItemToCart: (item) => { const itemExists = get().cartItems.find( (cartItem) => cartItem.id === item.id );
codeif (itemExists) { if (typeof itemExists.quantity === "number") { itemExists.quantity++; } set({ cartItems: [...get().cartItems] }); } else { set({ cartItems: [...get().cartItems, { ...item, quantity: 1 }] }); }},
increaseQuantity: (productId) => { const itemExists = get().cartItems.find( (cartItem) => cartItem.id === productId );
codeif (itemExists) { if (typeof itemExists.quantity === "number") { itemExists.quantity++; } set({ cartItems: [...get().cartItems] }); }}, decreaseQuantity: (productId) => { const itemExists = get().cartItems.find( (cartItem) => cartItem.id === productId );
codeif (itemExists) { if (typeof itemExists.quantity === "number") { if (itemExists.quantity === 1) { const updatedCartItems = get().cartItems.filter( (item) => item.id !== productId ); set({ cartItems: updatedCartItems }); } else { itemExists.quantity--; set({ cartItems: [...get().cartItems] }); } } }}, }));
export default useCartStore;
" add this
totalItems = 0 This returns the totaly quantity of items in the cart as an integer.
emptyCart() The emptyCart() method should be used to remove all cart items, and resetting cart totals to the default 0 values.
cartTotal = 0 This returns the total value of all items in the cart.
totalUniqueItems = 0 This returns the total unique items in the cart as an integer.
isEmpty = false A quick and easy way to check if the cart is empty. Returned as a boolean.
updateItem(itemId, data) The updateItem method should be used to update items in the cart. "
- Assistant