Created
May 16, 2023 09:41
-
-
Save yazinsai/7e6d73cffb4c1310a17e48820faa0173 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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