useLive.ts48 lines, 1.6 KB
| 1 | import { queryOptions, useQueryClient } from '@tanstack/react-query' |
| 2 | import { useEffect, useState } from 'react' |
| 3 | import { getSession } from '../../lib/api' |
| 4 | import { listen, type LiveEvent, type Status } from '../../lib/stream' |
| 5 | import { toast } from '../../lib/toast' |
| 6 | import { updatePost } from '../feed/posts' |
| 7 | import { unreadOptions } from '../notifications/unread' |
| 8 | |
| 9 | // The posts the stream announced. Only the stream writes this; |
| 10 | // nothing fetches it. |
| 11 | export const freshOptions = queryOptions({ |
| 12 | queryKey: ['fresh'], |
| 13 | queryFn: (): number[] => [], |
| 14 | staleTime: Infinity, |
| 15 | }) |
| 16 | |
| 17 | type News = { actor: string; post_id: number } |
| 18 | |
| 19 | // useLive keeps one stream open, and turns what it hears into changes |
| 20 | // to the cache. So nothing in the app has to poll. |
| 21 | export function useLive() { |
| 22 | const client = useQueryClient() |
| 23 | const [status, setStatus] = useState<Status>('away') |
| 24 | useEffect(() => { |
| 25 | const token = getSession()?.token |
| 26 | if (!token) return |
| 27 | |
| 28 | function onEvent(e: LiveEvent) { |
| 29 | const { actor, post_id: id }: News = JSON.parse(e.data) |
| 30 | if (e.event === 'post') { |
| 31 | client.setQueryData(freshOptions.queryKey, (ids = []) => |
| 32 | ids.includes(id) ? ids : [...ids, id], |
| 33 | ) |
| 34 | } |
| 35 | if (e.event === 'like') { |
| 36 | toast(`@${actor} liked your post`) |
| 37 | client.setQueryData(unreadOptions.queryKey, (n = 0) => n + 1) |
| 38 | updatePost(client, id, (p) => ({ ...p, likes: p.likes + 1 })) |
| 39 | client.invalidateQueries({ queryKey: ['notifications'] }) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | const stop = new AbortController() |
| 44 | listen(token, onEvent, setStatus, stop.signal) |
| 45 | return () => stop.abort() |
| 46 | }, [client]) |
| 47 | return status |
| 48 | } |