|
1 | | -import { useState } from 'react'; |
2 | | -import { useCoinGeckoSocket } from './useCoinGeckoSocket'; |
3 | | - |
4 | | -type PriceInfo = { |
5 | | - coinId: string; |
6 | | - price: number; |
7 | | - priceChangePercentage24h: number; |
8 | | - marketCap: number; |
9 | | - volume24h: number; |
10 | | - lastUpdated: number; |
11 | | -}; |
12 | | - |
13 | | -type PricesMap = Record<string, PriceInfo>; |
| 1 | +import { useEffect, useState } from 'react'; |
| 2 | +// import { subscribe } from '@/lib/websocket'; |
14 | 3 |
|
15 | 4 | export const useCoinPrice = (coinIds: string[]) => { |
16 | 5 | const [prices, setPrices] = useState<PricesMap>({}); |
17 | | - const [connected, setConnected] = useState(false); |
| 6 | + const coinIdsKey = coinIds.join(','); |
| 7 | + |
| 8 | + useEffect(() => { |
| 9 | + const cleanupFunctions: (() => void)[] = []; |
| 10 | + |
| 11 | + // Subscribe to each coin |
| 12 | + // coinIds.forEach((coinId) => { |
| 13 | + // const cleanup = subscribe(coinId, (allPrices) => { |
| 14 | + // setPrices(allPrices); |
| 15 | + // }); |
| 16 | + // cleanupFunctions.push(cleanup); |
| 17 | + // }); |
| 18 | + |
| 19 | + // Cleanup all subscriptions |
| 20 | + return () => { |
| 21 | + cleanupFunctions.forEach((cleanup) => cleanup()); |
| 22 | + }; |
| 23 | + |
| 24 | + }, [coinIdsKey]); // Use string key to avoid array reference changes |
18 | 25 |
|
19 | | - useCoinGeckoSocket({ |
20 | | - channel: 'CGSimplePrice', |
21 | | - subscribeParams: coinIds, |
22 | | - subscribeMessage: (coins) => ({ |
23 | | - command: 'message', |
24 | | - identifier: JSON.stringify({ channel: 'CGSimplePrice' }), |
25 | | - data: JSON.stringify({ action: 'set_tokens', coin_id: coins }), |
26 | | - }), |
27 | | - onReady: () => setConnected(true), |
28 | | - onData: (msg) => { |
29 | | - if (msg.c === 'C1' && msg.i && msg.p !== undefined) { |
30 | | - setPrices((prev) => ({ |
31 | | - ...prev, |
32 | | - [msg.i]: { |
33 | | - coinId: msg.i, |
34 | | - price: msg.p, |
35 | | - priceChangePercentage24h: msg.pp || 0, |
36 | | - marketCap: msg.m || 0, |
37 | | - volume24h: msg.v || 0, |
38 | | - lastUpdated: msg.t || Date.now() / 1000, |
39 | | - }, |
40 | | - })); |
41 | | - } |
42 | | - }, |
| 26 | + // Filter prices to only include requested coins |
| 27 | + const filteredPrices: PricesMap = {}; |
| 28 | + coinIds.forEach((coinId) => { |
| 29 | + if (prices[coinId]) { |
| 30 | + filteredPrices[coinId] = prices[coinId]; |
| 31 | + } |
43 | 32 | }); |
44 | 33 |
|
45 | | - return { prices, connected }; |
| 34 | + return { prices: filteredPrices }; |
46 | 35 | }; |
0 commit comments