no cookies or api call...

This commit is contained in:
DavidBelisle
2022-11-08 00:34:01 -05:00
parent 28fff14d96
commit 809ce36a1e
5 changed files with 57 additions and 28 deletions

View File

@@ -1,8 +1,10 @@
import { createContext, useState } from "react";
import { useCookies } from "react-cookie";
export const CartContext = createContext({
items: [],
getProductQuantity: () => { },
getProductRemaining: () => { },
addOneToCart: () => { },
removeOneFromCart: () => { },
deleteFromCart: () => { },
@@ -12,11 +14,12 @@ export const CartContext = createContext({
export function CartProvider({ children }) {
const [cookies, setCookie] = useCookies(['cart']);
const [cartProducts, setCartProducts] = useState([]);
function addToCart(product, qty) {
setCartProducts([...cartProducts, {...product, quantity: parseFloat(qty)}]);
setCartProducts([...cartProducts, { ...product, quantity: parseFloat(qty), remaining: parseFloat(product.quantity) }]);
}
function getProductQuantity(id) {
@@ -28,10 +31,20 @@ export function CartProvider({ children }) {
return quantity;
};
function addOneToCart(id, qty) {
const currentQty = getProductQuantity(id);
function getProductRemaining(id) {
const remaining = cartProducts.find(product => product.id === id)?.remaining;
if (remaining === undefined) {
return 0;
}
if (qty > currentQty) {
return remaining;
};
function addOneToCart(id) {
const currentQty = getProductQuantity(id);
const remaining = getProductRemaining(id);
if (remaining > currentQty) {
setCartProducts(
cartProducts.map(
product => product.id === id
@@ -46,7 +59,7 @@ export function CartProvider({ children }) {
const currentQty = getProductQuantity(id);
if (currentQty === 1)
deleteFromCart();
deleteFromCart(id);
else
setCartProducts(
cartProducts.map(
@@ -68,7 +81,7 @@ export function CartProvider({ children }) {
function getTotalCost() {
let totalCost = 0;
cartProducts.map((cartItem) => {
totalCost += (cartItem.Price * cartItem.quantity);
totalCost += (parseFloat(cartItem.price) * parseFloat(cartItem.quantity));
});
return totalCost;
@@ -77,6 +90,7 @@ export function CartProvider({ children }) {
const contextValue = {
items: cartProducts,
getProductQuantity,
getProductRemaining,
addOneToCart,
removeOneFromCart,
deleteFromCart,