26 lines
827 B
TypeScript
26 lines
827 B
TypeScript
import { useQueryClient } from '@tanstack/react-query'
|
|
import { useEffect } from 'react'
|
|
|
|
// Subscribes to the SSE stream (docs/phase1/01-architecture.md's realtime
|
|
// design) and invalidates the relevant queries on every event, so the UI
|
|
// updates the moment a new notification arrives without polling.
|
|
export function useNotificationStream() {
|
|
const queryClient = useQueryClient()
|
|
|
|
useEffect(() => {
|
|
const source = new EventSource('/api/v1/stream')
|
|
|
|
const invalidate = () => {
|
|
queryClient.invalidateQueries({ queryKey: ['notifications'] })
|
|
queryClient.invalidateQueries({ queryKey: ['topics'] })
|
|
}
|
|
|
|
source.addEventListener('notification.created', invalidate)
|
|
source.addEventListener('notification.updated', invalidate)
|
|
|
|
return () => {
|
|
source.close()
|
|
}
|
|
}, [queryClient])
|
|
}
|