-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
CartSummary.tsx
78 lines (67 loc) · 1.88 KB
/
CartSummary.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React, { useState, useEffect } from 'react'
import StripeTestCards from '../components/StripeTestCards'
import { useShoppingCart } from 'use-shopping-cart'
import { fetchPostJSON } from '../utils/api-helpers'
const CartSummary = () => {
const [loading, setLoading] = useState(false)
const [cartEmpty, setCartEmpty] = useState(true)
const [errorMessage, setErrorMessage] = useState('')
const {
formattedTotalPrice,
cartCount,
clearCart,
cartDetails,
redirectToCheckout,
} = useShoppingCart()
useEffect(() => setCartEmpty(!cartCount), [cartCount])
const handleCheckout: React.FormEventHandler<HTMLFormElement> = async (
event
) => {
event.preventDefault()
setLoading(true)
setErrorMessage('')
const response = await fetchPostJSON(
'/api/checkout_sessions/cart',
cartDetails
)
if (response.statusCode > 399) {
console.error(response.message)
setErrorMessage(response.message)
setLoading(false)
return
}
redirectToCheckout({ sessionId: response.id })
}
return (
<form onSubmit={handleCheckout}>
<h2>Cart summary</h2>
{errorMessage ? (
<p style={{ color: 'red' }}>Error: {errorMessage}</p>
) : null}
{/* This is where we'll render our cart */}
<p suppressHydrationWarning>
<strong>Number of Items:</strong> {cartCount}
</p>
<p suppressHydrationWarning>
<strong>Total:</strong> {formattedTotalPrice}
</p>
{/* Redirects the user to Stripe */}
<StripeTestCards />
<button
className="cart-style-background"
type="submit"
disabled={cartEmpty || loading}
>
Checkout
</button>
<button
className="cart-style-background"
type="button"
onClick={clearCart}
>
Clear Cart
</button>
</form>
)
}
export default CartSummary