Skip to content

Commit

Permalink
Merge pull request #32 from fac25/basket-page-contents
Browse files Browse the repository at this point in the history
Relates #12
  • Loading branch information
AlexPD93 authored Oct 27, 2022
2 parents 8414891 + d470cfc commit 86cb8c0
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 11 deletions.
46 changes: 38 additions & 8 deletions pages/basket.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";
import Image from "next/image";

const Basket = () => {
const [currentBasket, setCurrentBasket] = useState([]);
const [totalCost, setTotalCost] = useState(0);

useEffect(()=>{
const keys = Object.keys(localStorage)
const value = Object.values(localStorage)
useEffect(() => {
setCurrentBasket(JSON.parse(localStorage.getItem("basket")));

console.log(keys + "" + value)

},[])
let basketArray = JSON.parse(localStorage.getItem("basket"));
let total = basketArray.reduce((acc, current) => {
return current.price * current.quantity + acc;
}, 0);
setTotalCost(total);
}, []);

return <></>;
return (
<div>
<h1>Your current basket</h1>
<ul>
{currentBasket.map((item, index) => {
return (
<li key={index}>
<div>
<Image
src={"/images/" + item.image} // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt={item.name}
/>
<p>{item.name}</p>
<p>Price: £{item.price}</p>
<p>Quantity: {item.quantity}</p>
<p>Cost: £{item.quantity * item.price}</p>
</div>
</li>
);
})}
</ul>
<p>Overall total cost: £{totalCost}</p>
</div>
);
};

export default Basket;
15 changes: 12 additions & 3 deletions pages/products/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,17 @@ export async function getStaticProps({ params }) {
export default function Product({ product }) {
const handleBasket = (e) => {
e.preventDefault();
const number = document.getElementById("quantity").value
localStorage.setItem(JSON.stringify(product.name), number)

let localBasket = JSON.parse(localStorage.getItem("basket") || "[]");

localBasket.push({
name: product.name,
quantity: document.getElementById("quantity").value,
price: product.price,
image: product.src,
});

localStorage.setItem("basket", JSON.stringify(localBasket));
};

return (
Expand All @@ -58,7 +67,7 @@ export default function Product({ product }) {
<div>
<form>
<label htmlFor="quantity">Quantity</label>
<input type="number" id="quantity"/>
<input type="number" id="quantity" />
<button onClick={handleBasket}>Add to basket</button>
</form>
</div>
Expand Down

0 comments on commit 86cb8c0

Please sign in to comment.