diff --git a/src/pages/ChatSupport.jsx b/src/pages/ChatSupport.jsx new file mode 100644 index 0000000..814700a --- /dev/null +++ b/src/pages/ChatSupport.jsx @@ -0,0 +1,75 @@ +import axios from 'axios'; +import React, { useEffect, useRef, useState } from 'react'; +import './ChatSupport.css'; +const ChatSupport = () => { + const [messages, setMessages] = useState([]); + const [input, setInput] = useState(''); + const [loading, setLoading] = useState(false); + const chatEndRef = useRef(null); + // Function to scroll to the latest message + const scrollToBottom = () => { + chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + }; + // Function to send a message + const sendMessage = async () => { + if (input.trim() === '') return; + const userMessage = { sender: 'user', text: input }; + setMessages([...messages, userMessage]); + setInput(''); + setLoading(true); + try { + const response = await axios.post('/api/chat', { message: input }); + const botMessage = { sender: 'bot', text: response.data.reply }; + setMessages((prevMessages) => [...prevMessages, botMessage]); + } catch (error) { + const errorMessage = { sender: 'bot', text: 'Error: Could not send message. Please try again later.' }; + setMessages((prevMessages) => [...prevMessages, errorMessage]); + } finally { + setLoading(false); + scrollToBottom(); + } + }; + // Handle pressing the Enter key + const handleKeyPress = (e) => { + if (e.key === 'Enter') { + sendMessage(); + } + }; + + useEffect(() => { + scrollToBottom(); + }, [messages]); + + return ( +