1
1
'use client' ;
2
2
3
3
import { useChat } from 'ai/react' ;
4
- import { useEffect , useRef } from 'react' ;
4
+ import { useEffect , useRef , useState } from 'react' ;
5
5
import { BlockKind } from './block' ;
6
6
import { Suggestion } from '@/lib/db/schema' ;
7
7
import { initialBlockData , useBlock } from '@/hooks/use-block' ;
8
8
import { useUserMessageId } from '@/hooks/use-user-message-id' ;
9
9
import { cx } from 'class-variance-authority' ;
10
+ import { useSWRConfig } from 'swr' ;
10
11
11
12
type DataStreamDelta = {
12
13
type :
@@ -28,6 +29,19 @@ export function DataStreamHandler({ id }: { id: string }) {
28
29
const { setBlock } = useBlock ( ) ;
29
30
const lastProcessedIndex = useRef ( - 1 ) ;
30
31
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
+
31
45
useEffect ( ( ) => {
32
46
if ( ! dataStream ?. length ) return ;
33
47
@@ -93,6 +107,16 @@ export function DataStreamHandler({ id }: { id: string }) {
93
107
status : 'streaming' ,
94
108
} ;
95
109
110
+ case 'suggestion' :
111
+ setTimeout ( ( ) => {
112
+ setOptimisticSuggestions ( ( currentSuggestions ) => [
113
+ ...currentSuggestions ,
114
+ delta . content as Suggestion ,
115
+ ] ) ;
116
+ } , 0 ) ;
117
+
118
+ return draftBlock ;
119
+
96
120
case 'clear' :
97
121
return {
98
122
...draftBlock ,
0 commit comments