-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathuse-price.tsx
64 lines (56 loc) · 1.5 KB
/
use-price.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
import { useMemo } from 'react'
import { useCommerce } from '.'
export function formatPrice({
amount,
currencyCode,
locale,
}: {
amount: number
currencyCode: string
locale: string
}) {
const formatCurrency = new Intl.NumberFormat(locale, {
style: 'currency',
currency: currencyCode,
})
return formatCurrency.format(amount)
}
export function formatVariantPrice({
amount,
baseAmount,
currencyCode,
locale,
}: {
baseAmount: number
amount: number
currencyCode: string
locale: string
}) {
const hasDiscount = baseAmount > amount
const formatDiscount = new Intl.NumberFormat(locale, { style: 'percent' })
const discount = hasDiscount
? formatDiscount.format((baseAmount - amount) / baseAmount)
: null
const price = formatPrice({ amount, currencyCode, locale })
const basePrice = hasDiscount
? formatPrice({ amount: baseAmount, currencyCode, locale })
: null
return { price, basePrice, discount }
}
export default function usePrice(
data?: {
amount: number
baseAmount?: number
currencyCode: string
} | null
) {
const { amount, baseAmount, currencyCode } = data ?? {}
const { locale } = useCommerce()
const value = useMemo(() => {
if (typeof amount !== 'number' || !currencyCode) return ''
return baseAmount
? formatVariantPrice({ amount, baseAmount, currencyCode, locale })
: formatPrice({ amount, currencyCode, locale })
}, [amount, baseAmount, currencyCode])
return typeof value === 'string' ? { price: value } : value
}