-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-paddle-prices.tsx
53 lines (45 loc) · 1.44 KB
/
use-paddle-prices.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
import {
Paddle,
PricePreviewParams,
PricePreviewResponse,
} from "@paddle/paddle-js";
import { useEffect, useState } from "react";
import { PricingTier } from "@/constants/pricing-tier";
export type PaddlePrices = Record<string, string>;
function getLineItems(): PricePreviewParams["items"] {
const priceId = PricingTier.map((tier) => [
tier.priceId.month,
tier.priceId.year,
]);
return priceId.flat().map((priceId) => ({ priceId, quantity: 1 }));
}
function getPriceAmounts(prices: PricePreviewResponse) {
return prices.data.details.lineItems.reduce((acc, item) => {
acc[item.price.id] = item.formattedTotals.total;
return acc;
}, {} as PaddlePrices);
}
export function usePaddlePrices(
paddle: Paddle | undefined,
country: string
): { prices: PaddlePrices; loading: boolean } {
const [prices, setPrices] = useState<PaddlePrices>({});
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
const paddlePricePreviewRequest: Partial<PricePreviewParams> = {
items: getLineItems(),
...(country !== "OTHERS" && { address: { countryCode: country } }),
};
setLoading(true);
paddle
?.PricePreview(paddlePricePreviewRequest as PricePreviewParams)
.then((prices) => {
setPrices((prevState) => ({
...prevState,
...getPriceAmounts(prices),
}));
setLoading(false);
});
}, [country, paddle]);
return { prices, loading };
}