From fe06fc8b8af473e0195be7193e59beac09a65018 Mon Sep 17 00:00:00 2001 From: Mayo Date: Thu, 23 Mar 2023 16:42:17 +0100 Subject: [PATCH 1/2] general frontend optimization --- pages/index.tsx | 43 +++++++++++++++++++++++++++++------------- styles/Home.module.css | 4 ++-- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/pages/index.tsx b/pages/index.tsx index 03a182a8e..fd3410e72 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,4 +1,4 @@ -import { useRef, useState, useEffect, useMemo } from 'react'; +import { useRef, useState, useEffect, useMemo, useCallback } from 'react'; import Layout from '@/components/layout'; import styles from '@/styles/Home.module.css'; import { Message } from '@/types/chat'; @@ -18,6 +18,7 @@ export default function Home() { const [query, setQuery] = useState(''); const [loading, setLoading] = useState(false); const [sourceDocs, setSourceDocs] = useState([]); + const [error, setError] = useState(null); const [messageState, setMessageState] = useState<{ messages: Message[]; pending?: string; @@ -36,8 +37,6 @@ export default function Home() { const { messages, pending, history, pendingSourceDocs } = messageState; - console.log('messageState', messageState); - const messageListRef = useRef(null); const textAreaRef = useRef(null); @@ -49,6 +48,8 @@ export default function Home() { async function handleSubmit(e: any) { e.preventDefault(); + setError(null); + if (!query) { alert('Please input a question'); return; @@ -120,18 +121,22 @@ export default function Home() { }); } catch (error) { setLoading(false); + setError('An error occurred while fetching the data. Please try again.'); console.log('error', error); } } //prevent empty submissions - const handleEnter = (e: any) => { - if (e.key === 'Enter' && query) { - handleSubmit(e); - } else if (e.key == 'Enter') { - e.preventDefault(); - } - }; + const handleEnter = useCallback( + (e: any) => { + if (e.key === 'Enter' && query) { + handleSubmit(e); + } else if (e.key == 'Enter') { + e.preventDefault(); + } + }, + [query], + ); const chatMessages = useMemo(() => { return [ @@ -148,6 +153,13 @@ export default function Home() { ]; }, [messages, pending, pendingSourceDocs]); + //scroll to bottom of chat + useEffect(() => { + if (messageListRef.current) { + messageListRef.current.scrollTop = messageListRef.current.scrollHeight; + } + }, [chatMessages]); + return ( <> @@ -208,7 +220,7 @@ export default function Home() { className="flex-col" > {message.sourceDocs.map((doc, index) => ( -
+

Source {index + 1}

@@ -234,7 +246,7 @@ export default function Home() {
{sourceDocs.map((doc, index) => ( -
+

Source {index + 1}

@@ -296,9 +308,14 @@ export default function Home() {
+ {error && ( +
+

{error}

+
+ )}
-