After completing lesson 8 – Handle Add To Cart.
The popup is still not working when I click on “Add to Cart”
Ibrahima Answered question October 12, 2022

import Image from 'next/image'; import Link from 'next/link'; import React, { useContext } from 'react'; import { XCircleIcon } from '@heroicons/react/outline'; import Layout from '../components/Layout'; import { Store } from '../utils/Store'; import { useRouter } from 'next/router'; import dynamic from 'next/dynamic'; function CartScreen() { const router = useRouter(); const { state, dispatch } = useContext(Store); const { cart: { cartItems }, } = state; const removeItemHandler = (item) => { dispatch({ type: 'CART_REMOVE_ITEM', payload: item }); }; const updateCartHandler = (item, qty) => { const quantity = Number(qty); dispatch({ type: 'CART_ADD_ITEM', payload: { ...item, quantity } }); }; return ( <Layout title="Shopping cart"> <h1 className="mb-4 text-xl">Shopping Cart</h1> {cartItems.length === 0 ? ( <div> Cart is empty. <Link href="/">Go shopping</Link> </div> ) : ( <div className="grid md:grid-cols-4 md:gap-5"> <div className="overflow-x-auto md:col-span-3"> <table className="min-w-full"> <thead className="border-b"> <tr> <th className="px-5 text-left">Item</th> <th className="px-5 text-right">quantity</th> <th className="px-5 text-right">Price</th> <th className="px-5">Action</th> </tr> </thead> <tbody> {cartItems.map((item) => ( <tr key={item.slug} className="border-b"> <td> <Link href={`/product/${item.slug}`}> <a className="flex items-center"> <Image src={item.image} alt={item.name} width={50} heigh={50} ></Image> {item.name} </a> </Link> </td> <td className="p-5 text-right"> <select value={item.quantity} onChange={(e) => updateCartHandler(item, e.target.value) } > {[...Array(item.countInStock).keys()].map((x) => ( <option key={x + 1} value={x + 1}> {x + 1} </option> ))} </select> </td> <td className="p-5 text-right">${item.price}</td> <td className="p-5 text-center"> <button onClick={() => removeItemHandler(item)}> <XCircleIcon classname="h-5 w-5"></XCircleIcon> </button> </td> </tr> ))} </tbody> </table> </div> <div className="card p-5"> <ul> <li> <div className="pb-3 text-xl"> Subtotal ({cartItems.reduce((a, c) => a + c.quantity, 0)}) : $ {cartItems.reduce((a, c) => a + c.quantity * c.price, 0)} </div> </li> <li> <button onClick={() => router.push('login?redirect=/shiping')} className="primary-button w-full" > Check Out </button> </li> </ul> </div> </div> )} </Layout> ); } export default dynamic(() => Promise.resolve(CartScreen), { ssr: false });
Ibrahima Answered question October 12, 2022
hello there,
please compare your code with this:
https://github.com/basir/react-18-shopping-cart/blob/master/src/App.js#L10
share the code you use to add the item to the cart.
Bassir Answered question October 11, 2022
Thank you Basir,
When I click on Add to cart 🛒, it doesn’t work , I get redirected to the cart page with nothing inside.