Skip to content

Commit 6c23a8a

Browse files
fix: handle suggestion stream parts (#700)
1 parent aa29cc5 commit 6c23a8a

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

components/data-stream-handler.tsx

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
'use client';
22

33
import { useChat } from 'ai/react';
4-
import { useEffect, useRef } from 'react';
4+
import { useEffect, useRef, useState } from 'react';
55
import { BlockKind } from './block';
66
import { Suggestion } from '@/lib/db/schema';
77
import { initialBlockData, useBlock } from '@/hooks/use-block';
88
import { useUserMessageId } from '@/hooks/use-user-message-id';
99
import { cx } from 'class-variance-authority';
10+
import { useSWRConfig } from 'swr';
1011

1112
type DataStreamDelta = {
1213
type:
@@ -28,6 +29,19 @@ export function DataStreamHandler({ id }: { id: string }) {
2829
const { setBlock } = useBlock();
2930
const lastProcessedIndex = useRef(-1);
3031

32+
const { mutate } = useSWRConfig();
33+
const [optimisticSuggestions, setOptimisticSuggestions] = useState<
34+
Array<Suggestion>
35+
>([]);
36+
37+
useEffect(() => {
38+
if (optimisticSuggestions && optimisticSuggestions.length > 0) {
39+
const [optimisticSuggestion] = optimisticSuggestions;
40+
const url = `/api/suggestions?documentId=${optimisticSuggestion.documentId}`;
41+
mutate(url, optimisticSuggestions, false);
42+
}
43+
}, [optimisticSuggestions, mutate]);
44+
3145
useEffect(() => {
3246
if (!dataStream?.length) return;
3347

@@ -93,6 +107,16 @@ export function DataStreamHandler({ id }: { id: string }) {
93107
status: 'streaming',
94108
};
95109

110+
case 'suggestion':
111+
setTimeout(() => {
112+
setOptimisticSuggestions((currentSuggestions) => [
113+
...currentSuggestions,
114+
delta.content as Suggestion,
115+
]);
116+
}, 0);
117+
118+
return draftBlock;
119+
96120
case 'clear':
97121
return {
98122
...draftBlock,

0 commit comments

Comments
 (0)