useCurrencies.ts raw

   1  import React from "react";
   2  import useSWR from "swr";
   3  
   4  import { Currency } from "src/types";
   5  import { swrFetcher } from "src/utils/swr";
   6  
   7  export function useCurrencies(includeSats = false) {
   8    const { data: ratesData, isLoading } = useSWR<Currency[]>(
   9      "/api/alby/currencies",
  10      swrFetcher
  11    );
  12  
  13    const currencies = React.useMemo(() => {
  14      if (!ratesData) {
  15        return [];
  16      }
  17  
  18      if (includeSats) {
  19        return [
  20          ["SATS", "sats"],
  21          ...ratesData
  22            .filter(({ iso_code }) => iso_code !== "BTC")
  23            .sort((a, b) => {
  24              const priorityDiff = a.priority - b.priority;
  25              return priorityDiff !== 0
  26                ? priorityDiff
  27                : a.iso_code.localeCompare(b.iso_code);
  28            })
  29            .map(({ iso_code, name }): [string, string] => [iso_code, name]),
  30        ];
  31      }
  32  
  33      return ratesData
  34        .filter(({ iso_code }) => iso_code !== "BTC")
  35        .map(({ iso_code, name }): [string, string] => [iso_code, name])
  36        .sort((a, b) => a[1].localeCompare(b[1]));
  37    }, [ratesData, includeSats]);
  38  
  39    return {
  40      currencies,
  41      isLoading,
  42    };
  43  }
  44