Use source loader for email sprite icons
[ProtonMail-WebClient.git] / packages / wallet / store / hooks / useExchangeRate.ts
blob055adf08c332090d9b55510384a298b84e0a67c0
1 import { useCallback, useEffect } from 'react';
3 import { createSelector } from '@reduxjs/toolkit';
5 import type { WasmApiExchangeRate, WasmFiatCurrencySymbol } from '@proton/andromeda';
6 import { baseUseSelector } from '@proton/react-redux-store';
7 import { createHooks } from '@proton/redux-utilities';
9 import { exchangeRateThunk, selectExchangeRate } from '../slices';
10 import { getKeyAndTs } from '../slices/exchangeRate';
12 export const exchangeRateHooks = createHooks(exchangeRateThunk, selectExchangeRate);
14 export const useGetExchangeRate = () => {
15     const get = exchangeRateHooks.useGet();
16     return useCallback(
17         async (fiat: WasmFiatCurrencySymbol, date?: Date) => {
18             const results = await get({ thunkArg: [fiat, date] });
19             const [key] = getKeyAndTs(fiat, date);
21             return results[key];
22         },
23         [get]
24     );
27 export const useExchangeRate = (fiat: WasmFiatCurrencySymbol) => {
28     const getExchangeRate = useGetExchangeRate();
29     const [, loading] = exchangeRateHooks.useValue();
31     const exchangeRateSimpleSelector = createSelector(
32         selectExchangeRate,
33         (result): [WasmApiExchangeRate | undefined, boolean] => {
34             const { value } = result;
36             const rate = value?.[fiat];
38             return [rate, loading];
39         }
40     );
42     useEffect(() => {
43         void getExchangeRate(fiat);
44     }, [fiat, getExchangeRate]);
46     return baseUseSelector(exchangeRateSimpleSelector);