may need to backtrack?

This commit is contained in:
Mikayla Dobson
2022-07-07 14:10:00 -05:00
parent a8a7daeddb
commit 31446f3cd0
2 changed files with 15 additions and 51 deletions

View File

@@ -12,62 +12,26 @@ function Cart() {
const [data, setData] = useState<any>(); const [data, setData] = useState<any>();
const [subtotal, setSubtotal] = useState('loading...'); const [subtotal, setSubtotal] = useState('loading...');
// on mount
useEffect(() => {
if (!state) return;
dispatch({ type: ActionType.UPDATESUBTOTAL, payload: getSubtotal(data) });
}, []);
useEffect(() => {
console.log(state.cart);
setSubtotal(state.cart.subtotal);
}, [state.cart.subtotal]);
useEffect(() => {
if (!state.cart.contents) return;
let newProducts: Array<Product> = [];
for (let item of state.cart.contents) {
const withQuantity = {
...item,
quantity: 1
}
const foundItem = newProducts.findIndex((res) => res.name === item.name);
if (foundItem === -1) {
newProducts.push(withQuantity);
} else {
// @ts-ignore
newProducts[foundItem].quantity += 1;
}
}
for (let item of newProducts) {
if (typeof item.quantity !== 'number') {
throw new Error("Quantity is possibly undefined in Cart.tsx");
}
item.quantity = item.quantity / 2;
}
setData(newProducts);
}, [state]);
const updateQuantity = useCallback((product: Product, newQuantity: number) => {
const updated = product;
updated.quantity = newQuantity;
}, []);
return ( return (
<Page> <Page>
{ {
state.user.firstName ? state.user.firstName ?
<h1>Hello, {state.user.firstName}!</h1> <h1>Hello, {state.user.firstName}!</h1>
: :
<h1>Your cart is empty! Please <a href='/login'>log in</a> to build your own.</h1> <h1>Please <a href='/login'>log in</a> to start your cart.</h1>
} }
<section id="cart-contents"> <section id="cart-contents">
{ data && data.map((product: Product) => <CartItem key={v4()} updateQuantity={updateQuantity} product={product} />) } { state.cart &&
<>
<p>You have {state.cart.contents.length} items in your cart!</p>
<div>
{state.cart.contents.map((product: Product) => <CartItem key={v4()} product={product} />)}
</div>
</>
}
</section> </section>
<section id="subtotal"> <section id="subtotal">

View File

@@ -1,12 +1,12 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { v4 } from "uuid"; import { v4 } from "uuid";
function CartItem({ product, updateQuantity }: any) { function CartItem({ product }: any) {
const [quantity, setQuantity] = useState(product.quantity || 0); const [quantity, setQuantity] = useState(product.quantity || 0);
useEffect(() => { // useEffect(() => {
updateQuantity(product, quantity); // updateQuantity(product, quantity);
}, [quantity]); // }, [quantity]);
return ( return (
<div className="cart-item-panel"> <div className="cart-item-panel">