Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client-mount-hydrate.tsx

41 lines1.3 KB

1import { useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4​
5/**
6 * A server-authoritative chat (`persistence: true`) that mounts on the client,
7 * after hydration, like a chat that waits for a thread id from localStorage.
8 *
9 * React Strict Mode replays the effects of a client mount (attach, detach,
10 * attach). A component hydrated from the server render does not get that
11 * replay, so `/persistence-durability` cannot show it. The GET answers with
12 * the `server-interrupt` scenario's pending interrupt.
13 */
14const connection = fetchServerSentEvents(
15 '/api/persistence-durability?scenario=server-interrupt',
17​
18export const Route = createFileRoute('/client-mount-hydrate')({
19 component: ClientMountHydratePage,
20})
21​
22function ClientMountHydratePage() {
23 const [mounted, setMounted] = useState(false)
24 useEffect(() => setMounted(true), [])
25 return (
26 <div data-testid="client-mount-hydrate-page" style={{ padding: 16 }}>
27 {mounted ? <Chat /> : null}
28 </div>
29 )
31​
32function Chat() {
33 const { interrupts } = useChat({
34 threadId: 'client-mount-hydrate',
35 connection,
36 persistence: true,
37 })
38 return (
39 <div data-testid="interrupt-count" data-count={String(interrupts.length)} />
40 )