Almost ready le carosse

This commit is contained in:
DavidBelisle
2022-11-07 23:36:19 -05:00
parent 75ab07a355
commit 48f77de441
6 changed files with 314 additions and 115 deletions

View File

@@ -0,0 +1,94 @@
import { createContext, useState } from "react";
export const CartContext = createContext({
items: [],
getProductQuantity: () => { },
addOneToCart: () => { },
removeOneFromCart: () => { },
deleteFromCart: () => { },
getTotalCost: () => { },
addToCart: () => { }
});
export function CartProvider({ children }) {
const [cartProducts, setCartProducts] = useState([]);
function addToCart(product, qty) {
setCartProducts([...cartProducts, {...product, quantity: parseFloat(qty)}]);
}
function getProductQuantity(id) {
const quantity = cartProducts.find(product => product.id === id)?.quantity;
if (quantity === undefined) {
return 0;
}
return quantity;
};
function addOneToCart(id, qty) {
const currentQty = getProductQuantity(id);
if (qty > currentQty) {
setCartProducts(
cartProducts.map(
product => product.id === id
? { ...product, quantity: parseFloat(product.quantity) + 1 }
: product
)
);
}
};
function removeOneFromCart(id) {
const currentQty = getProductQuantity(id);
if (currentQty === 1)
deleteFromCart();
else
setCartProducts(
cartProducts.map(
product => product.id === id
? { ...product, quantity: parseFloat(product.quantity) - 1 }
: product
)
);
};
function deleteFromCart(id) {
setCartProducts(
cartProducts => cartProducts.filter(currentProduct => {
return currentProduct.id != id;
})
);
};
function getTotalCost() {
let totalCost = 0;
cartProducts.map((cartItem) => {
totalCost += (cartItem.Price * cartItem.quantity);
});
return totalCost;
};
const contextValue = {
items: cartProducts,
getProductQuantity,
addOneToCart,
removeOneFromCart,
deleteFromCart,
getTotalCost,
addToCart
};
return (
<CartContext.Provider value={contextValue}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;