This repository was archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathCartSummary.tsx
71 lines (60 loc) · 1.66 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
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 {
formattedTotalPrice,
cartCount,
clearCart,
cartDetails,
redirectToCheckout,
} = useShoppingCart();
useEffect(() => setCartEmpty(!cartCount), [cartCount]);
const handleCheckout: React.FormEventHandler<HTMLFormElement> = async (
event
) => {
event.preventDefault();
setLoading(true);
const response = await fetchPostJSON(
'/api/checkout_sessions/cart',
cartDetails
);
if (response.statusCode === 500) {
console.error(response.message);
return;
}
redirectToCheckout({ sessionId: response.id });
};
return (
<form onSubmit={handleCheckout}>
<h2>Cart summary</h2>
{/* 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;