#Adding a loading indicator at the end of string while a streamed message arrives

1 messages · Page 1 of 1 (latest)

elder bough
#

The following code works great for animating the streamed message that arrives from the Open AI:s API, but I want to add a loading indicator that has the same funciton as a cursor at the end of the message while it's typing, just like ChatGPT has. Does anyone know how to achieve this?

`const MemoizedContent = React.memo(({ role, htmlContent, isStreaming, messageId }) => {
const [displayContent, setDisplayContent] = useState('');
const contentRef = useRef(null);
const lastUpdateRef = useRef(0);
const animationFrameRef = useRef(null);

useEffect(() => {
if (!isStreaming) {
setDisplayContent(htmlContent);
return;
}

const updateContent = (timestamp) => {
  if (timestamp - lastUpdateRef.current > 1) {  // Increased speed
    const charsToAdd = Math.min(1, htmlContent.length - displayContent.length);  // Add up to 5 chars at once
    const newContent = htmlContent.slice(0, displayContent.length + charsToAdd);
    setDisplayContent(newContent);
    lastUpdateRef.current = timestamp;
  }

  if (displayContent.length < htmlContent.length) {
    animationFrameRef.current = requestAnimationFrame(updateContent);
  }
};

animationFrameRef.current = requestAnimationFrame(updateContent);

return () => {
  if (animationFrameRef.current) {
    cancelAnimationFrame(animationFrameRef.current);
  }
};

}, [htmlContent, isStreaming, displayContent]);

useEffect(() => {
if (contentRef.current) {
contentRef.current.scrollTop = contentRef.current.scrollHeight;
}
}, [displayContent]);

return (
<Paper
ref={contentRef}

>
  <Typography 
    variant="body1"   >
    <span dangerouslySetInnerHTML={{ __html: displayContent }} />
    {isStreaming && displayContent.length < htmlContent.length}
  </Typography>
</Paper>

);
});`

boreal coral