diff --git a/pages/basket.js b/pages/basket.js index f58d3c2..69b27a4 100644 --- a/pages/basket.js +++ b/pages/basket.js @@ -5,70 +5,38 @@ import Link from "next/link"; const Basket = () => { const [currentBasket, setCurrentBasket] = useState([]); const [totalCost, setTotalCost] = useState(0); - const [currentQuantities, setQuantities] = useState(new Array(7).fill(null)); useEffect(() => { - setCurrentBasket(JSON.parse(localStorage.getItem("basket"))); + setCurrentBasket(JSON.parse(localStorage.getItem("basket"))); - let basketArray = JSON.parse(localStorage.getItem("basket")); - let total = basketArray.reduce((acc, current) => { - return current.price * current.quantity + acc; - }, 0); - setTotalCost(total); - - basketArray.forEach((item) => { - //set state - setQuantities((previousQuantities) => { - console.log(item.id); - let nextQuantities = previousQuantities; - nextQuantities[item.id - 1] = item.quantity; - return nextQuantities; - }); - }); + let basketArray = JSON.parse(localStorage.getItem("basket")); + let total = basketArray.reduce((acc, current) => { + return current.price * current.quantity + acc; + }, 1000); + setTotalCost(total); }, []); - function incrementItem(event) { - event.preventDefault(); - //get the product name and current quantity - let nameWithoutPlus = event.target.id.slice(4); - let indexOfItemNameFirstLetter = nameWithoutPlus.search(/[a-zA-Z]/); - let name = nameWithoutPlus.slice( - indexOfItemNameFirstLetter, - nameWithoutPlus.length - 1 - ); - let preUpdatedQuantity = nameWithoutPlus.slice( - 0, - indexOfItemNameFirstLetter - ); - let productId = nameWithoutPlus.slice(nameWithoutPlus.length - 1); - - //update state - let copy = [...currentQuantities]; - console.log(copy); - copy[productId - 1] = parseFloat(preUpdatedQuantity) + 1; - setQuantities(() => { - return copy; - }); - - // setQuantities((previousQuantities) => { - // let nextQuantities = previousQuantities; - // nextQuantities[productId - 1] = parseFloat(preUpdatedQuantity) + 1; - // console.log(nextQuantities); - // return nextQuantities; - // }); - - //update localstorage - } - function decrementItem(event) { - //get the product name and current quantity - let name = event.target.id.slice(5); - console.log(name); - - //update state and localstorage - } - - console.log(currentQuantities); + const handleQuantity = (e) => { + let checkBasket = currentBasket + if (e.target.id === "plus") { + checkBasket.map((item) => { + if (e.target.value === item.name) { + item.quantity = Number(item.quantity) + 1; + setCurrentBasket(checkBasket); + } + }); + } else if (e.target.id === "minus") { + checkBasket.map((item) => { + if (Number(item.quantity) > 0) { + if (e.target.value === item.name) { + checkBasket.quantity = Number(item.quantity) - 1; + setCurrentBasket(checkBasket); + } + } + }); + } + }; return (
{item.name}
Price: £{item.price}
-+
Cost: £{item.quantity * item.price}