matt HOFFNER
SSE get request
eef247f
raw
history blame
1.24 kB
import { useEffect, useState } from "react";
export default function WebSearchPage({ searchParams }) {
const [aiResponse, setAiResponse] = useState("");
const [eventSource, setEventSource] = useState(null);
useEffect(() => {
if (!searchParams || !searchParams.searchTerm) return;
const { searchTerm, start = "1" } = searchParams;
const url = new URL('/api/llm', window.location.origin);
url.search = new URLSearchParams({ question: searchTerm, startIndex: start });
// No need to make a fetch request. Directly open the EventSource connection.
const es = new EventSource(url);
setEventSource(es);
return () => {
if (es) es.close(); // Close the EventSource when the component is unmounted.
};
}, [searchParams]);
// Add event listener for the EventSource
useEffect(() => {
if (eventSource) {
eventSource.onmessage = (event) => {
setAiResponse(prev => prev + event.data);
};
eventSource.onerror = (event) => {
console.error("EventSource failed:", event);
};
}
return () => {
if (eventSource) {
eventSource.close();
}
};
}, [eventSource]);
console.log(aiResponse);
return <>{aiResponse}</>;
}