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 { Button, useToast } from '@chakra-ui/react'
import { useRouter } from 'next/router'
import { getAuth } from '~/libs/auth'
import { upsertUserCart } from '~/services/cart'
type Props = {
variantId: number | null,
quantity?: number;
source?: 'buy' | 'add_to_cart';
}
const AddToCart = ({
variantId,
quantity = 1,
source = 'add_to_cart'
}: Props) => {
const auth = getAuth()
const router = useRouter()
const toast = useToast({
position: 'top',
isClosable: true
})
const handleClick = async () => {
if (typeof auth !== 'object') {
const currentUrl = encodeURIComponent(router.asPath)
router.push(`/login?next=${currentUrl}`)
return;
}
if (
!variantId ||
isNaN(quantity) ||
typeof auth !== 'object'
) return;
toast.promise(
upsertUserCart({
userId: auth.id,
type: 'product',
id: variantId,
qty: quantity,
selected: true,
source: source,
qtyAppend: true
}),
{
loading: { title: 'Menambahkan ke keranjang', description: 'Mohon tunggu...' },
success: { title: 'Menambahkan ke keranjang', description: 'Berhasil menambahkan ke keranjang belanja' },
error: { title: 'Menambahkan ke keranjang', description: 'Gagal menambahkan ke keranjang belanja' },
}
)
if (source === 'buy') {
router.push('/shop/checkout?source=buy')
}
}
const btnConfig = {
'add_to_cart': {
colorScheme: 'yellow',
text: 'Keranjang'
},
'buy': {
colorScheme: 'red',
text: 'Beli'
}
}
return (
<Button onClick={handleClick} colorScheme={btnConfig[source].colorScheme} className='w-full'>
{btnConfig[source].text}
</Button>
)
}
export default AddToCart
|