import React, { useState, useEffect, useRef } from 'react'; import { useAuth } from '../services/AuthContext'; import { useNavigate } from 'react-router-dom'; const processMessages = (messageObject) => { return (previousMessages) => { if (previousMessages.length > 0 && previousMessages[previousMessages.length - 1].sender === messageObject.sender) { const newMessage = {text:previousMessages[previousMessages.length - 1].text+ ' ' + messageObject.text, sender: messageObject.sender}; return [...previousMessages.slice(0, -1), newMessage]; } else { return [...previousMessages, messageObject]; } } } const ChatApi = () => { const { token, logout } = useAuth(); const navigate = useNavigate(); const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const sendMessage = (e) => { e.preventDefault(); if (!input.trim()) return; const message = { type: 'message', content: input }; setMessages(processMessages({ text: input, sender: 'user' })); fetch('http://localhost:8000/api/message', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ message: input }) }).then(response => response.json()).then(data => { setMessages(processMessages({ text: data.message?.content, sender: 'ai' })); }); setInput(''); }; // Rest of your component (file upload handler, UI rendering, etc.) return (
{/* Messages area */}
{(messages || []).map((message, index) => (
{message.text}
))}
{/* Input area */}
setInput(e.target.value)} placeholder="Type your message..." className="flex-1 p-2 border rounded" />
); }; export default ChatApi;