usePollSubscriptions.ts
1 import { apiConnector } from '@/lib/api/connector' 2 import { ApiMessageType } from '@/lib/api/types' 3 import { PollOptionType } from '@/types/qna.types' 4 import { loadPollOptions } from '@/utils/api.utils' 5 import { useSetAtom } from 'jotai' 6 import { useEffect } from 'react' 7 import { pollOptionsRecordAtom } from '../atoms/pollOption' 8 9 // Hook for managing poll-specific subscriptions and data loading 10 export const usePollSubscriptions = (pollId: string) => { 11 const setPollOptionsRecord = useSetAtom(pollOptionsRecordAtom) 12 13 useEffect(() => { 14 if (!pollId) return 15 16 loadPollOptions({ pollId, setPollOptionsRecord }) 17 18 // Set up poll-specific subscriptions 19 const pollVoteSub = apiConnector.subscribe<PollOptionType>( 20 ApiMessageType.POLL_VOTE_MESSAGE, 21 (option) => { 22 if (option.pollId === pollId) { 23 setPollOptionsRecord((prev: Record<string, PollOptionType>) => ({ 24 ...prev, 25 [option.id]: option, 26 })) 27 } 28 }, 29 { pollId }, 30 ) 31 32 return () => { 33 pollVoteSub() 34 } 35 }, [pollId, setPollOptionsRecord]) 36 }