useStreamController
Stream Controller
Usage
import React, { useState, useRef } from "react";
import useStreamController from 'funda-ui/Utils/useStreamController';
const App = () => {
const streamController = useStreamController({
onChunk: async (chunk: string, index: number) => {
// start (Execute it only once)
if (index === 0) {
}
// Streaming data is JSON split by rows
const lines = chunk.split("\n").filter(line => line.trim() !== "");
// Process each data chunk
console.log('Received chunk:', chunk);
},
onComplete: async (lastContent: string) => {
// Process when stream is completed
console.log('Stream completed');
// Display AI reply
console.log('AI reply:', lastContent);
},
onError: (error) => {
// Error handling
console.error('Stream error:', error);
},
onAbort: () => {
// Abort processing
console.log('Stream aborted');
}
});
useEffect(() => {
// Start stream
const response = await fetch(url);
await streamController.start(response);
// Pause stream
streamController.pause();
// Resume stream
streamController.resume();
// Abort stream
streamController.abort();
// Check status
const isActive = streamController.isActive();
const isPaused = streamController.isPaused();
}, []);
};