import { useQueryClient } from '@tanstack/react-query' import { useEffect } from 'react' import { apiBaseUrl } from '@/lib/api-client' import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events' /** * Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes * the affected queries whenever another member adds or buys an item, invites * somebody or renames the list — so the page updates without a reload. * * The session cookie is sent via `withCredentials`. `EventSource` reconnects on * its own; a `ready` event is emitted on every (re)connection, used here to * reconcile anything missed while disconnected. */ export function useListEvents(listId: string) { const queryClient = useQueryClient() useEffect(() => { const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, { withCredentials: true, }) const onReady = () => { queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }) } source.addEventListener('ready', onReady) const listeners = LIST_EVENT_TYPES.map((type) => { const listener = () => { for (const queryKey of queryKeysForListEvent(type, listId)) { queryClient.invalidateQueries({ queryKey }) } } source.addEventListener(type, listener) return { type, listener } }) return () => { source.removeEventListener('ready', onReady) for (const { type, listener } of listeners) source.removeEventListener(type, listener) source.close() } }, [listId, queryClient]) }