Almost ready le carosse
This commit is contained in:
94
GrossesMitaines/grosses-mitaines-ui/src/components/Cart.js
Normal file
94
GrossesMitaines/grosses-mitaines-ui/src/components/Cart.js
Normal 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;
|
Reference in New Issue
Block a user