mango-v4-ui/hooks/useCoingecko.ts

51 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-02-27 23:20:11 -08:00
/* eslint-disable @typescript-eslint/no-explicit-any */
2022-11-18 11:11:06 -08:00
import { useQuery } from '@tanstack/react-query'
import { Token } from 'types/jupiter'
import useJupiterMints from './useJupiterMints'
const fetchCoingecko = async (
2023-07-21 11:47:53 -07:00
mangoTokens: Token[],
2022-11-18 11:11:06 -08:00
): Promise<{ prices: any[]; symbol: string }[]> => {
const coingeckoIds = mangoTokens.map((token) => ({
id: token.extensions?.coingeckoId,
symbol: token.symbol,
}))
2023-01-20 08:13:03 -08:00
2022-11-18 11:11:06 -08:00
const promises: any = []
for (const token of coingeckoIds) {
if (token.id) {
promises.push(
fetch(
2023-07-21 11:47:53 -07:00
`https://api.coingecko.com/api/v3/coins/${token.id}/market_chart?vs_currency=usd&days=1`,
2023-01-20 08:13:03 -08:00
).then((res) =>
2023-07-21 11:47:53 -07:00
res.json().then((r) => ({ ...r, symbol: token.symbol })),
),
2022-11-18 11:11:06 -08:00
)
}
}
const data = await Promise.all(promises)
return data || []
}
export const useCoingecko = () => {
const { mangoTokens } = useJupiterMints()
const res = useQuery<any[], Error>(
['coingecko-tokens'],
2023-01-20 08:13:03 -08:00
() => fetchCoingecko(mangoTokens),
2022-11-18 11:11:06 -08:00
{
2023-01-20 08:13:03 -08:00
cacheTime: 1000 * 60 * 15,
staleTime: 1000 * 60 * 10,
retry: 3,
enabled: !!mangoTokens?.length,
refetchOnWindowFocus: false,
2023-07-21 11:47:53 -07:00
},
2022-11-18 11:11:06 -08:00
)
return {
isLoading: res.isLoading,
data: res.data || [],
}
}