11import { IonContent , IonHeader , IonPage , IonTitle , IonToolbar } from '@ionic/react' ;
22import { useTranslation } from 'react-i18next' ;
3- import { useState , useEffect } from 'react' ;
3+ import { useState , useEffect , useRef } from 'react' ;
4+ import { useLocation } from 'react-router-dom' ;
45import ChatContainer from '../../common/components/Chat/ChatContainer' ;
56import ChatInput from '../../common/components/Chat/ChatInput' ;
67import { chatService } from '../../common/services/ChatService' ;
@@ -16,19 +17,51 @@ import './ChatPage.scss';
1617const ChatPage = ( ) : JSX . Element => {
1718 const { t } = useTranslation ( ) ;
1819 const [ messages , setMessages ] = useState < ChatMessageData [ ] > ( [ ] ) ;
20+ const location = useLocation ( ) ;
21+ const prevPathRef = useRef ( location . pathname ) ;
1922
20- // Reset chat session when component unmounts
23+ const resetChatState = ( ) => {
24+ setMessages ( [ ] ) ;
25+ } ;
26+
27+ // Handle initial setup and cleanup
2128 useEffect ( ( ) => {
22- // Create a new session when the component mounts
23- chatService . resetSession ( ) ;
29+ // Create a new session when the component mounts using an IIFE
30+ ( async ( ) => {
31+ await chatService . resetSession ( ) ;
32+ resetChatState ( ) ;
33+ } ) ( ) ;
2434
2535 // Reset the chat session when the component unmounts
2636 return ( ) => {
37+ // We need to call this synchronously in the cleanup function
38+ // but we can at least trigger the reset process
2739 chatService . resetSession ( ) ;
28- // We don't need to clear messages array since the component is unmounting
40+ resetChatState ( ) ;
2941 } ;
3042 } , [ ] ) ;
3143
44+ // Listen for route changes to reset chat when navigating away
45+ useEffect ( ( ) => {
46+ // If we came back to this page from another route, reset the chat
47+ if ( prevPathRef . current !== location . pathname && location . pathname === '/tabs/chat' ) {
48+ // We're returning to the chat page
49+ ( async ( ) => {
50+ await chatService . resetSession ( ) ;
51+ resetChatState ( ) ;
52+ } ) ( ) ;
53+ }
54+
55+ // If we're navigating away, reset chat state
56+ if ( prevPathRef . current === '/tabs/chat' && location . pathname !== '/tabs/chat' ) {
57+ chatService . resetSession ( ) ;
58+ resetChatState ( ) ;
59+ }
60+
61+ // Update ref for next comparison
62+ prevPathRef . current = location . pathname ;
63+ } , [ location . pathname ] ) ;
64+
3265 const handleSendMessage = async ( text : string ) => {
3366 const userMessage = chatService . createUserMessage ( text ) ;
3467 setMessages ( prevMessages => [ ...prevMessages , userMessage ] ) ;
0 commit comments