From fe372eb6fbba4682d1cd3304ae04dd2727a4badd Mon Sep 17 00:00:00 2001 From: michael Date: Tue, 18 Jun 2024 13:09:50 +0800 Subject: [PATCH] fix conditional useEffect --- .../src/components/pending-messages.tsx | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/jupyter-ai/src/components/pending-messages.tsx b/packages/jupyter-ai/src/components/pending-messages.tsx index d1f5c0ddc..12824e10d 100644 --- a/packages/jupyter-ai/src/components/pending-messages.tsx +++ b/packages/jupyter-ai/src/components/pending-messages.tsx @@ -43,24 +43,28 @@ function PendingMessageElement(props: PendingMessageElementProps): JSX.Element { export function PendingMessages( props: PendingMessagesProps ): JSX.Element | null { - if (props.messages.length === 0) { - return null; - } - const [timestamp, setTimestamp] = useState(''); - const lastMessage = props.messages[props.messages.length - 1]; - const agentMessage: AiService.AgentChatMessage = { - type: 'agent', - id: lastMessage.id, - time: lastMessage.time, - body: '', - reply_to: '', - persona: lastMessage.persona - }; + const [agentMessage, setAgentMessage] = + useState(null); useEffect(() => { + if (props.messages.length === 0) { + setAgentMessage(null); + setTimestamp(''); + return; + } + const lastMessage = props.messages[props.messages.length - 1]; + setAgentMessage({ + type: 'agent', + id: lastMessage.id, + time: lastMessage.time, + body: '', + reply_to: '', + persona: lastMessage.persona + }); + // timestamp format copied from ChatMessage - const newTimestamp = new Date(agentMessage.time * 1000).toLocaleTimeString( + const newTimestamp = new Date(lastMessage.time * 1000).toLocaleTimeString( [], { hour: 'numeric', @@ -68,7 +72,11 @@ export function PendingMessages( } ); setTimestamp(newTimestamp); - }, [agentMessage]); + }, [props.messages]); + + if (!agentMessage) { + return null; + } return ( - {props.messages.map((message) => ( + {props.messages.map(message => (