Skip to content

Instantly share code, notes, and snippets.

@yazinsai
Created May 16, 2023 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yazinsai/7e6d73cffb4c1310a17e48820faa0173 to your computer and use it in GitHub Desktop.
Save yazinsai/7e6d73cffb4c1310a17e48820faa0173 to your computer and use it in GitHub Desktop.
function StreamedText() {
const [text, setText] = React.useState("");
React.useEffect(() => { getStream() }, []);
function getStream() {
// Fetch the stream
const stream = await fetch('/api/answer', { method: 'POST', body: JSON.stringify({ query } }) })
const data = stream.body;
if (!data) return;
// Display the response
const reader = data.getReader();
const decoder = new TextDecoder();
let done = false;
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
const chunkValue = decoder.decode(value);
setText((prev) => prev + chunkValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment