React Streaming Hooks
If you want a lightweight React hook for streaming text from Setu without pulling in large framework dependencies, here is a production-ready hook:
Custom useSetuStream Hook
typescript
import { useState, useCallback } from 'react';
export function useSetuStream() {
const [output, setOutput] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState<string | null>(null);
const send = useCallback(async (prompt: string) => {
setIsStreaming(true);
setOutput('');
setError(null);
try {
const res = await fetch('/api/chat-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt }),
});
if (!res.ok) throw new Error(`HTTP error ${res.status}`);
if (!res.body) throw new Error('ReadableStream not supported');
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n').filter((l) => l.trim().startsWith('data: '));
for (const line of lines) {
const data = line.replace(/^data:\s*/, '').trim();
if (data === '[DONE]') break;
try {
const parsed = JSON.parse(data);
const token = parsed.choices?.[0]?.delta?.content || '';
setOutput((prev) => prev + token);
} catch {
// Partial json frame
}
}
}
} catch (err: any) {
setError(err.message || 'Stream failed');
} finally {
setIsStreaming(false);
}
}, []);
return { output, isStreaming, error, send };
}