import React, { useEffect, useMemo, useState } from 'react'; import { IonBadge, IonButton, IonButtons, IonChip, IonContent, IonHeader, IonIcon, IonPage, IonText, IonTitle, IonToolbar, useIonViewWillEnter, } from '@ionic/react'; import { addOutline, cartOutline, removeOutline, star } from 'ionicons/icons'; import { RouteComponentProps, useHistory } from 'react-router-dom'; import { CartItem, products, readCart, writeCart } from './Home'; import { setStatusBarBackground, setStatusBarStyle, Style, } from '../utils/statusBar'; type Props = RouteComponentProps<{ id: string }>; const ProductDetail: React.FC = ({ match }) => { const history = useHistory(); const [quantity, setQuantity] = useState(1); const [message, setMessage] = useState(''); const [cartCount, setCartCount] = useState(0); useIonViewWillEnter(() => { setStatusBarStyle(Style.Dark); setStatusBarBackground('#ffffff'); const count = readCart().reduce((sum, item) => sum + item.quantity, 0); setCartCount(count); }); useEffect(() => { const syncCount = () => { const count = readCart().reduce((sum, item) => sum + item.quantity, 0); setCartCount(count); }; syncCount(); window.addEventListener('storage', syncCount); window.addEventListener('cart:updated', syncCount as EventListener); return () => { window.removeEventListener('storage', syncCount); window.removeEventListener('cart:updated', syncCount as EventListener); }; }, []); const product = useMemo( () => products.find((item) => item.id === match.params.id), [match.params.id] ); const showMessage = (text: string) => { setMessage(text); window.setTimeout(() => setMessage(''), 4000); }; const addToCart = () => { if (!product) return; const cart: CartItem[] = readCart(); const existing = cart.find((item) => item.id === product.id); const nextCart = existing ? cart.map((item) => item.id === product.id ? { ...item, quantity: item.quantity + quantity } : item ) : [ ...cart, { id: product.id, name: product.name, price: product.price, quantity, }, ]; writeCart(nextCart); showMessage('Added to cart'); }; if (!product) { return ( history.replace('/home')}> Back Product

Product not found

This product is no longer available.

history.replace('/home')}> Browse products
); } return ( history.replace('/home')}> Back {product.name} history.push('/cart')} > {cartCount}
{product.imageAlt}
{product.category}

{product.name}

{product.rating} Ready in {product.prepTime}

{product.description}

${product.price.toFixed(2)}

Choose quantity

setQuantity((value) => Math.max(1, value - 1))} > {quantity} setQuantity((value) => value + 1)} >

Total

${(product.price * quantity).toFixed(2)}
Add to cart
{message && (

{message}

)} history.push('/cart')} > Go to cart
); }; export default ProductDetail;