Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useChat } from '@tanstack/ai-react'
4import { Send, Square } from 'lucide-react'
5import { chatFn } from '@/lib/server-fns'
6
7export const Route = createFileRoute('/server-fn-chat')({
8 component: ServerFnChat,
9})
10
11function ServerFnChat() {
12 const { messages, sendMessage, isLoading, error, stop } = useChat({
13 threadId: 'server-fn-chat',
14 fetcher: ({ messages, threadId }, { signal }) =>
15 chatFn({ data: { messages, threadId }, signal }),
16 })
17 const [input, setInput] = useState('')
18
19 const handleSubmit = (e: React.FormEvent) => {
20 e.preventDefault()
21 if (!input.trim() || isLoading) return
22 void sendMessage(input)
23 setInput('')
24 }
25
26 return (
27 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-950 text-gray-100">
28 <div className="border-b border-gray-800 bg-gray-900/60 px-4 py-3">
29 <h2 className="text-lg font-semibold">Chat via server function</h2>
30 <p className="text-xs text-gray-400 mt-1">
31 <code className="text-cyan-400">
32 useChat({ fetcher: ({'{'}messages, threadId{'}'}, {'{'}signal
33 {'}'}) => chatFn({'{'} data: {'{'} messages, threadId {'}'},
34 signal {'}'}) })
35 </code>{' '}
36 — the server function returns an SSE{' '}
37 <code className="text-cyan-400">Response</code>; the chat client
38 parses it.
39 </p>
40 </div>
41
42 <div className="flex-1 overflow-y-auto p-4 space-y-3">
43 {messages.length === 0 && (
44 <p className="text-gray-500 text-sm">
45 Say something to start the chat.
46 </p>
47 )}
48 {messages.map((m) => (
49 <div
50 key={m.id}
51 className={`max-w-2xl rounded-lg px-3 py-2 ${
52 m.role === 'user'
53 ? 'ml-auto bg-cyan-700/40 border border-cyan-600/40'
54 : 'mr-auto bg-gray-800 border border-gray-700'
55 }`}
56 >
57 {m.parts.map((part, i) =>
58 part.type === 'text' ? <span key={i}>{part.content}</span> : null,
59 )}
60 </div>
61 ))}
62 {error && (
63 <div className="rounded-lg border border-red-700/60 bg-red-900/30 px-3 py-2 text-sm text-red-200">
64 {error.message}
65 </div>
66 )}
67 </div>
68
69 <form
70 onSubmit={handleSubmit}
71 className="border-t border-gray-800 bg-gray-900/80 p-3 flex gap-2"
72 >
73 <input
74 type="text"
75 value={input}
76 onChange={(e) => setInput(e.target.value)}
77 placeholder="Message..."
78 disabled={isLoading}
79 className="flex-1 rounded-lg bg-gray-800 border border-gray-700 px-3 py-2 text-sm focus:outline-none focus:border-cyan-500"
80 />
81 {isLoading ? (
82 <button
83 type="button"
84 onClick={stop}
85 className="px-3 py-2 rounded-lg bg-red-600 hover:bg-red-700 text-white"
86 aria-label="Stop"
87 >
88 <Square size={18} />
89 </button>
90 ) : (
91 <button
92 type="submit"
93 disabled={!input.trim()}
94 className="px-3 py-2 rounded-lg bg-cyan-600 hover:bg-cyan-700 disabled:opacity-50 text-white"
95 aria-label="Send"
96 >
97 <Send size={18} />
98 </button>
99 )}
100 </form>
101 </div>
102 )
103}