useMarketData.ts 952 B

12345678910111213141516171819202122232425262728293031
  1. 'use client';
  2. import { useEffect, useRef } from 'react';
  3. import { useSignalRContext } from '@/contexts/signalrProvider';
  4. export default function useMarketData(market: string) {
  5. const { cryptoConnection, cryptoConnected } = useSignalRContext();
  6. const prevMarketRef = useRef<string | null>(null);
  7. useEffect(() => {
  8. if (!cryptoConnection || !cryptoConnected || !market) {
  9. return;
  10. }
  11. // 이전 마켓 구독 해제
  12. if (prevMarketRef.current && prevMarketRef.current !== market) {
  13. cryptoConnection.invoke('UnsubscribeMarket', prevMarketRef.current).catch(() => {});
  14. }
  15. // 새 마켓 구독
  16. cryptoConnection.invoke('SubscribeMarket', market).catch(console.error);
  17. prevMarketRef.current = market;
  18. return () => {
  19. if (prevMarketRef.current) {
  20. cryptoConnection.invoke('UnsubscribeMarket', prevMarketRef.current).catch(() => {});
  21. prevMarketRef.current = null;
  22. }
  23. };
  24. }, [cryptoConnection, cryptoConnected, market]);
  25. }