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