Open History to see the last commit
1import ReactDOM from 'react-dom/client'
2import {
3 QueryClient,
4 QueryClientProvider,
5 useQuery,
6} from '@tanstack/react-query'
7import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
8β
9import './style.css'
10import { useState } from 'react'
11import { chatQueryOptions } from './chat'
12import { Message } from './message'
13β
14const queryClient = new QueryClient()
15β
16export default function App() {
17 return (
18 <QueryClientProvider client={queryClient}>
19 <ReactQueryDevtools />
20 <Example />
21 </QueryClientProvider>
22 )
23}
24β
25function ChatMessage({ question }: { question: string }) {
26 const { error, data = [], isFetching } = useQuery(chatQueryOptions(question))
27β
28 if (error) return 'An error has occurred: ' + error.message
29β
30 return (
31 <div>
32 <Message message={{ content: question, isQuestion: true }} />
33 <Message
34 inProgress={isFetching}
35 message={{ content: data.join(' '), isQuestion: false }}
36 />
37 </div>
38 )
39}
40β
41function Example() {
42 const [questions, setQuestions] = useState<Array<string>>([])
43 const [currentQuestion, setCurrentQuestion] = useState('')
44β
45 const submitMessage = () => {
46 setQuestions([...questions, currentQuestion])
47 setCurrentQuestion('')
48 }
49β
50 return (
51 <div className="flex flex-col h-screen max-w-3xl mx-auto p-4">
52 <h1 className="text-3xl font-bold text-gray-800">
53 TanStack Chat Example
54 </h1>
55 <div className="overflow-y-auto mb-4 space-y-4">
56 {questions.map((question) => (
57 <ChatMessage key={question} question={question} />
58 ))}
59 </div>
60β
61 <div className="flex items-center space-x-2">
62 <input
63 className="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-100"
64 value={currentQuestion}
65 onChange={(e) => setCurrentQuestion(e.target.value)}
66 onKeyDown={(e) => {
67 if (e.key === 'Enter') {
68 submitMessage()
69 }
70 }}
71 placeholder="Type your message..."
72 />
73 <button
74 onClick={submitMessage}
75 disabled={!currentQuestion.trim()}
76 className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold px-4 py-2 rounded-2xl shadow-md transition"
77 >
78 <span>Send</span>
79 <svg
80 xmlns="http://www.w3.org/2000/svg"
81 width="24"
82 height="24"
83 viewBox="0 0 24 24"
84 fill="none"
85 stroke="currentColor"
86 stroke-width="2"
87 stroke-linecap="round"
88 stroke-linejoin="round"
89 >
90 <path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z" />
91 <path d="m21.854 2.147-10.94 10.939" />
92 </svg>
93 </button>
94 </div>
95 </div>
96 )
97}
98β
99const rootElement = document.getElementById('root')
100if (!rootElement) throw new Error('Missing #root element')
101ReactDOM.createRoot(rootElement).render(<App />)