Working tree is now the canonical repo. Off-chain play-money + trustless on-chain (FPMM AMM + CLOB via UMA settlement), AI market factory, creator/social/distribution, mobile shell + push, one-command demo + deploy-kit. Secrets excluded (see ENV-AND-KEYS.md). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { db } from 'web/lib/supabase/db'
|
|
import { orderBy, uniqBy } from 'lodash'
|
|
import { usePersistentLocalState } from './use-persistent-local-state'
|
|
import { useEffect } from 'react'
|
|
import { useApiSubscription } from 'client-common/hooks/use-api-subscription'
|
|
import { ChatMessage, convertPublicChatMessage } from 'common/chat-message'
|
|
|
|
export function usePublicChat(channelId: string, limit: number) {
|
|
const [messages, setMessages] = usePersistentLocalState<
|
|
ChatMessage[] | undefined
|
|
>(undefined, `public-chat-messages-${limit}-v2-${channelId}`)
|
|
|
|
const [newestId, setNewestId] = usePersistentLocalState<number | undefined>(
|
|
undefined,
|
|
`public-chat-newest-id`
|
|
)
|
|
|
|
const fetchMessages = async () => {
|
|
const { data } = await db
|
|
.from('chat_messages')
|
|
.select('*')
|
|
.eq('channel_id', channelId)
|
|
.order('created_time', { ascending: false })
|
|
.gt('id', newestId ?? 0)
|
|
.limit(limit)
|
|
|
|
if (data) {
|
|
const newMessages = data.map(convertPublicChatMessage)
|
|
setMessages((prevMessages) =>
|
|
orderBy(
|
|
uniqBy([...newMessages, ...(prevMessages ?? [])], (m) => m.id),
|
|
'createdTime',
|
|
'desc'
|
|
)
|
|
)
|
|
|
|
if (data.length > 0) setNewestId(data[0].id)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchMessages()
|
|
}, [limit])
|
|
|
|
useApiSubscription({
|
|
topics: ['public-chat'],
|
|
onBroadcast: () => {
|
|
fetchMessages()
|
|
},
|
|
})
|
|
|
|
return messages
|
|
}
|