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

chat.ts

33 lines866 Bytes

1import {
2 queryOptions,
3 experimental_streamedQuery as streamedQuery,
4} from '@tanstack/react-query'
5​
6const answers = [
7 "I'm just an example chat, I can't really answer any questions :(".split(' '),
8 'TanStack is great. Would you like to know more?'.split(' '),
9]
10​
11function chatAnswer(_question: string) {
12 return {
13 async *[Symbol.asyncIterator]() {
14 const answer = answers[Math.floor(Math.random() * answers.length)]
15 let index = 0
16 while (index < answer.length) {
17 await new Promise((resolve) =>
18 setTimeout(resolve, 100 + Math.random() * 300),
19 )
20 yield answer[index++]
21 }
22 },
23 }
25​
26export const chatQueryOptions = (question: string) =>
27 queryOptions({
28 queryKey: ['chat', question],
29 queryFn: streamedQuery({
30 streamFn: () => chatAnswer(question),
31 }),
32 staleTime: Infinity,
33 })