DEV Community

Bastien Moriel
Bastien Moriel

Posted on

react checkout practice

import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import './Checkout.css'

function Checkout({ user }) {
const location = useLocation()
const navigate = useNavigate()
const basket = location.state?.basket || []
const [success, setSuccess] = useState(false)
const [error, setError] = useState('')

const total = basket.reduce((sum, item) => {
return sum + item.product_price * item.quantity
}, 0)

const placeOrder = async () => {
if (!user) { navigate('/login'); return }

const res = await fetch('/api/orders', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    customerID: user.customerID,
    items: basket.map(item => ({
      productID: item.productID,
      quantity:  item.quantity
    }))
  })
})

const data = await res.json()
if (!res.ok) { setError(data.error); return }
setSuccess(true)
Enter fullscreen mode Exit fullscreen mode

}

if (success) {
return (


Order Placed!


Thank you for your order.


navigate('/orders')}>
View My Orders


)
}

return (


Checkout


{basket.length === 0 ?

Your basket is empty.

: (
<>
{basket.map((item, index) => (

{item.product_name}


Quantity: {item.quantity}


£{(item.product_price * item.quantity).toFixed(2)}



))}

Total: £{total.toFixed(2)}



{error &&

{error}

}
Place Order
</>
)}

)
}

export default Checkout

.page { padding: 30px; }
.page h1 { margin-bottom: 20px; }

.checkout-item {
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
margin-bottom: 10px;
max-width: 500px;
}

.item-name { font-weight: 700; margin-bottom: 5px; color: #144A5C; }

.checkout-total { margin: 20px 0; }
.checkout-total h2 { color: #A2C24A; }

.error {
color: white;
background: red;
padding: 10px;
border-radius: 6px;
margin-bottom: 10px;
}

.order-btn {
background: #A2C24A;
color: white;
border: none;
padding: 12px 30px;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
font-family: 'Gluten', cursive;
}

Top comments (0)