-
Notifications
You must be signed in to change notification settings - Fork 4
/
useGetFiatAmount.ts
73 lines (61 loc) · 1.92 KB
/
useGetFiatAmount.ts
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
import { fiat } from "@getalby/lightning-tools";
import React from "react";
import { useAppStore } from "~/lib/state/appStore";
let cachedRates: Record<string, number> = {};
function useFiatRate() {
const fiatCurrency = useAppStore((store) => store.fiatCurrency) || "USD";
const [rate, setRate] = React.useState<number>();
React.useEffect(() => {
(async () => {
try {
if (cachedRates[fiatCurrency]) {
setRate(cachedRates[fiatCurrency]);
return;
}
setRate(undefined);
const rate = await fiat.getFiatBtcRate(fiatCurrency);
setRate(rate);
cachedRates[fiatCurrency] = rate;
} catch (error) {
console.error(error);
}
})();
}, [fiatCurrency]);
return rate;
}
export function useGetFiatAmount() {
const fiatCurrency = useAppStore((store) => store.fiatCurrency) || "USD";
const rate = useFiatRate();
const getFiatAmount = React.useCallback(
(amount: number, displayCurrencySign = true) => {
if (rate) {
if (displayCurrencySign) {
return `${new Intl.NumberFormat(undefined, {
style: "currency",
currency: fiatCurrency,
currencyDisplay: "narrowSymbol",
}).format(rate * amount)}`;
}
const amountWithCurrencyCode = new Intl.NumberFormat("en-US", {
style: "currency",
currency: fiatCurrency,
currencyDisplay: "code",
}).format(rate * amount);
return amountWithCurrencyCode.substring(
amountWithCurrencyCode.search(/\s/) + 1,
);
}
return undefined;
},
[rate, fiatCurrency],
);
return rate ? getFiatAmount : undefined;
}
export function useGetSatsAmount() {
const rate = useFiatRate();
const getSatsAmount = React.useCallback(
(fiatAmount: number) => (rate ? Math.round(fiatAmount / rate) : undefined),
[rate],
);
return rate ? getSatsAmount : undefined;
}