Skip to content
Snippets Groups Projects

Finalisation du panier

Merged Princelle Maxime requested to merge develop into main
Compare and
14 files
+ 844
71
Preferences
Compare changes
Files
14
+ 59
0
import { Dispatch } from 'react';
import { Product, ActionType } from './CartTypes';
export function addToCart(cart: Product[], dispatch: Dispatch<ActionType>, product: Product): Product[] {
let newCart: Product[] = cart;
// Check if product already exists in cart, then update quantity
const existingProduct = newCart.find(p => p.name === product.name);
if (existingProduct) {
existingProduct.quantity = existingProduct.quantity ? existingProduct.quantity + 1 : 1;
existingProduct.stockPrice = existingProduct.price * existingProduct.quantity;
return setCart(newCart, dispatch);
}
// If not, add product to cart
return setCart([...cart, { ...product, quantity: 1, stockPrice: product.price}], dispatch);
}
export function removeFromCart(cart: Product[], dispatch: Dispatch<ActionType>, product: Product): Product[] {
let newCart: Product[] = cart;
// Check if product already exists in cart, then update quantity
const existingProduct = newCart.find(p => p.name === product.name);
if (existingProduct) {
existingProduct.quantity = existingProduct.quantity ? existingProduct.quantity - 1 : 0;
existingProduct.stockPrice = existingProduct.price * existingProduct.quantity;
// If quantity is 0, remove product from cart
if (existingProduct.quantity === 0) {
return setCart(newCart.filter(p => p.name !== product.name), dispatch);
}
return setCart(newCart, dispatch);
}
return setCart(cart, dispatch);
}
export function updateProductQuantity(cart: Product[], dispatch: Dispatch<ActionType>, product: Product, quantity: number): Product[] {
let newCart: Product[] = cart;
// Check if product already exists in cart, then update quantity
const existingProduct = newCart.find(p => p.name === product.name);
if (existingProduct) {
existingProduct.quantity = quantity;
existingProduct.stockPrice = existingProduct.price * quantity;
if (existingProduct.quantity === 0) {
return setCart(newCart.filter(p => p.name !== product.name), dispatch);
}
return setCart(newCart, dispatch);
}
return setCart(newCart, dispatch);
}
function setCart(newCart: Product[], dispatch: Dispatch<ActionType>): Product[]{
dispatch({ type: 'SET_CART', payload: newCart });
return newCart;
}
\ No newline at end of file