Skip to content

Commit

Permalink
fix: handle suggestion stream parts
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyphilemon committed Jan 13, 2025
1 parent aa29cc5 commit 70c3819
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion components/data-stream-handler.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use client';

import { useChat } from 'ai/react';
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { BlockKind } from './block';
import { Suggestion } from '@/lib/db/schema';
import { initialBlockData, useBlock } from '@/hooks/use-block';
import { useUserMessageId } from '@/hooks/use-user-message-id';
import { cx } from 'class-variance-authority';
import { useSWRConfig } from 'swr';

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

const { mutate } = useSWRConfig();
const [optimisticSuggestions, setOptimisticSuggestions] = useState<
Array<Suggestion>
>([]);

useEffect(() => {
if (optimisticSuggestions && optimisticSuggestions.length > 0) {
const [optimisticSuggestion] = optimisticSuggestions;
const url = `/api/suggestions?documentId=${optimisticSuggestion.documentId}`;
mutate(url, optimisticSuggestions, false);
}
}, [optimisticSuggestions, mutate]);

useEffect(() => {
if (!dataStream?.length) return;

Expand Down Expand Up @@ -93,6 +107,16 @@ export function DataStreamHandler({ id }: { id: string }) {
status: 'streaming',
};

case 'suggestion':
setTimeout(() => {
setOptimisticSuggestions((currentSuggestions) => [
...currentSuggestions,
delta.content as Suggestion,
]);
}, 0);

return draftBlock;

case 'clear':
return {
...draftBlock,
Expand Down

0 comments on commit 70c3819

Please sign in to comment.