108 lines
2.8 KiB
JavaScript
108 lines
2.8 KiB
JavaScript
import { createContext, useState } from "react";
|
|
import { useCookies } from "react-cookie";
|
|
|
|
export const CartContext = createContext({
|
|
items: [],
|
|
getProductQuantity: () => { },
|
|
getProductRemaining: () => { },
|
|
addOneToCart: () => { },
|
|
removeOneFromCart: () => { },
|
|
deleteFromCart: () => { },
|
|
getTotalCost: () => { },
|
|
addToCart: () => { }
|
|
});
|
|
|
|
export function CartProvider({ children }) {
|
|
|
|
const [cartCookie,setCartCookie] = useCookies(['cart'])
|
|
const [cartProducts, setCartProducts] = useState([]);
|
|
|
|
function addToCart(product, qty) {
|
|
|
|
setCartProducts([...cartProducts, { ...product, quantity: parseFloat(qty), remaining: parseFloat(product.quantity) }]);
|
|
}
|
|
|
|
function getProductQuantity(id) {
|
|
const quantity = cartProducts.find(product => product.id === id)?.quantity;
|
|
if (quantity === undefined) {
|
|
return 0;
|
|
}
|
|
|
|
return quantity;
|
|
};
|
|
|
|
function getProductRemaining(id) {
|
|
const remaining = cartProducts.find(product => product.id === id)?.remaining;
|
|
if (remaining === undefined) {
|
|
return 0;
|
|
}
|
|
|
|
return remaining;
|
|
};
|
|
|
|
function addOneToCart(id) {
|
|
const currentQty = getProductQuantity(id);
|
|
const remaining = getProductRemaining(id);
|
|
|
|
if (remaining > 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(id);
|
|
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 += (parseFloat(cartItem.price) * parseFloat(cartItem.quantity));
|
|
});
|
|
|
|
return totalCost;
|
|
};
|
|
|
|
const contextValue = {
|
|
items: cartProducts,
|
|
getProductQuantity,
|
|
getProductRemaining,
|
|
addOneToCart,
|
|
removeOneFromCart,
|
|
deleteFromCart,
|
|
getTotalCost,
|
|
addToCart
|
|
};
|
|
|
|
return (
|
|
<CartContext.Provider value={contextValue}>
|
|
{children}
|
|
</CartContext.Provider>
|
|
);
|
|
}
|
|
|
|
export default CartProvider; |