import { useChat } from '../hooks/useChat';
import { useContext, useEffect, useState } from 'react';
import UserContext from '../contexts/UserContext';
function ChatList() {
const { chatsList, newChat, deleteChat } = useChat();
const { user } = useContext(UserContext);
const [chats, setChats] = useState([]);
// Load user's chats
useEffect(() => {
const loadChats = async () => {
const userChats = await chatsList(user);
if (Array.isArray(userChats)) {
setChats(userChats);
}
};
loadChats();
}, [user, chatsList]);
// Create new chat
const handleNewChat = async () => {
const chatData = { userId: user.id, title: 'Nueva conversación' };
const result = await newChat(chatData);
if (typeof result === 'object') {
setChats([...chats, result]);
}
};
// Delete chat
const handleDeleteChat = async (chatId) => {
const result = await deleteChat(chatId);
if (result === 'Chat eliminado') {
setChats(chats.filter(chat => chat.id !== chatId));
}
};
return (
<div>
<button onClick={handleNewChat}>New Chat</button>
<ul>
{chats.map(chat => (
<li key={chat.id}>
{chat.title}
<button onClick={() => handleDeleteChat(chat.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}