import { useQueryClient } from '@tanstack/react-query' import { useEffect } from 'react' import { queryKeysForListEvent } from '@/lib/list-events' import { subscribeToListEvents } from '@/lib/list-events-stream' /** * Follows 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. The connection is shared with * any other subscriber of the same list (see `list-events-stream.ts`). * * Pass `undefined` to follow nothing (e.g. while the primary list is unknown). */ export function useListEvents(listId: string | undefined) { const queryClient = useQueryClient() useEffect(() => { if (!listId) return return subscribeToListEvents(listId, { onEvent: (type) => { for (const queryKey of queryKeysForListEvent(type, listId)) { void queryClient.invalidateQueries({ queryKey }) } }, onReady: () => { void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }) }, }) }, [listId, queryClient]) }