historical messages are now fetched from api

This commit is contained in:
slawk0
2024-11-02 23:13:40 +01:00
parent 96f87c2fe8
commit 39a4242176
6 changed files with 80 additions and 71 deletions

View File

@@ -52,7 +52,7 @@ export async function sendContact(contact: string) {
export async function getMessages(
contact: string | null,
): Promise<MessagesProps[]> {
if (contact !== null) {
if (contact == null) {
return [];
}
try {

View File

@@ -1,5 +1,4 @@
import { useForm, SubmitHandler } from 'react-hook-form';
import { useEffect } from 'react';
import { sendContact } from '../../api/contactsApi.tsx';
type Input = {
@@ -24,18 +23,6 @@ function ContactForm({
}: InitializeContactsProps) {
const { register, handleSubmit, reset } = useForm<Input>();
useEffect(() => {
const storedContact = localStorage.getItem('contact');
if (storedContact) {
InitializeContact(storedContact);
}
window.onscroll = () => {
window.scrollY === 0 && console.log('scrolled to top');
return () => window.onscroll == null;
};
}, []);
const submitContact: SubmitHandler<Input> = (data) => {
const contact = data.contact.toLowerCase().trim();
sendContact(contact);

View File

@@ -1,4 +1,3 @@
import zdjecie from '../../../assets/walter.png';
import profile from '../../../assets/profile.svg';
type Contact = {
contact: string | null;

View File

@@ -36,30 +36,28 @@ function ContactsList({
});
}
const fetchContacts = async () => {
const contacts: ContactsProps[] = await getContactsList();
console.log('Fetching contacts list');
console.log(contacts);
contacts.forEach(contactHandler);
};
useEffect(() => {
if (!socket) {
console.error('Socket not initialized');
return;
}
async function fetchContacts() {
try {
const contacts: ContactsProps[] = await getContactsList();
contacts.forEach(contactHandler);
} catch (error) {
console.error('Error fetching contacts:', error);
}
}
fetchContacts();
fetchContacts().catch((e) =>
console.error('Failed to fetch contacts: ', e),
);
return () => {
if (!socket) {
console.error('Socket not initialized');
return;
}
socket.off('get contacts list');
socket.off('contact');
};
}, []);
@@ -79,38 +77,36 @@ function ContactsList({
return 0;
});
const addContactsList = sortedContacts.map(
(contact: ContactsProps, index) => (
<li
className="flex hover:bg-green-700 p-2 rounded cursor-pointer justify-between items-center min-h-[40px]"
onClick={() => {
InitializeContact(contact.usernamecontact);
updateContactStatus(contact, true);
const addContactsList = sortedContacts.map((contact: ContactsProps) => (
<li
className="flex hover:bg-green-700 p-2 rounded cursor-pointer justify-between items-center min-h-[40px]"
onClick={() => {
InitializeContact(contact.usernamecontact);
updateContactStatus(contact, true);
}}
key={contact.usernamecontact}
>
<span className="flex-shrink-0">{contact.usernamecontact}</span>
<div className="w-4 h-4 mx-2 flex items-center justify-center mr-auto">
<p className="text-center text-2xl text-red-200 leading-none">
{contact.read ? '' : '•'}
</p>
</div>
<button
onClick={(e) => {
e.stopPropagation();
removeContact(contact.usernamecontact);
setCurrentContact(null);
localStorage.removeItem('contact');
}}
key={index}
className="flex-shrink-0 w-6 h-6 rounded-full hover:text-red-500 flex items-center justify-center text-gray-500"
>
<span className="flex-shrink-0">{contact.usernamecontact}</span>
<div className="w-4 h-4 mx-2 flex items-center justify-center mr-auto">
<p className="text-center text-2xl text-red-200 leading-none">
{contact.read ? '' : '•'}
</p>
</div>
<button
onClick={(e) => {
e.stopPropagation();
removeContact(contact.usernamecontact);
setCurrentContact(null);
localStorage.removeItem('contact');
}}
className="flex-shrink-0 w-6 h-6 rounded-full hover:text-red-500 flex items-center justify-center text-gray-500"
>
x
</button>
</li>
),
);
x
</button>
</li>
));
return (
<div className="flex-grow overflow-y-auto w-64">
<ul className="items-center text-center ml-1 mt-2 flex-grow-1">

View File

@@ -2,7 +2,6 @@ import { useEffect, useRef } from 'react';
import { socket } from '../../socket/socket.tsx';
import { useOutletContext } from 'react-router-dom';
import { UsernameType } from '../../utils/ProtectedRoutes.tsx';
import { getMessages } from '../../api/contactsApi.tsx';
type ChatMessages = {
sender: string;
message: string;
@@ -33,23 +32,27 @@ function MessagesArea({
}: MessagesAreaProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);
const { username }: UsernameType = useOutletContext();
function messageHandler(msg: ChatMessages) {
setMessages((prevMessages) => {
// Check if the message already exists in the state
if (!prevMessages.some((m) => m.message_id === msg.message_id)) {
return [...prevMessages, msg];
}
return prevMessages;
});
}
useEffect(() => {
if (!socket) {
console.error('Socket not initialized');
return;
}
getMessages(currentContact);
function messageHandler(msg: ChatMessages) {
setMessages((prevMessages) => {
// Check if the message already exists in the state
if (!prevMessages.some((m) => m.message_id === msg.message_id)) {
return [...prevMessages, msg];
}
return prevMessages;
});
}
window.onscroll = () => {
window.scrollY === 0 && console.log('scrolled to top');
return () => window.onscroll == null;
};
socket.on('chat message', (msg: ChatMessages) => {
console.log('Received message: ', msg);

View File

@@ -36,13 +36,19 @@ function Chat() {
if (token) {
initializeSocket(token);
}
const storedContact = localStorage.getItem('contact');
if (storedContact) {
InitializeContact(storedContact);
}
}, []);
function InitializeContact(newContact: string) {
setMessages([]); // Clear messages from previous contact
localStorage.setItem('contact', newContact); // Set current contact in localstorage
setCurrentContact(newContact); // Set state for current user (used in contactProfile.tsx
getMessages(newContact);
setCurrentContact(newContact); // Set state for current user (used in contactProfile.tsx)
fetchMessages(newContact).catch((e) =>
console.error('Failed to fetch messages: ', e),
);
setContactsList((prevContacts) =>
prevContacts.map((c) =>
c.usernamecontact === newContact ? { ...c, read: true } : c,
@@ -52,6 +58,24 @@ function Chat() {
console.log('Current contact is now: ', newContact);
}
const fetchMessages = async (currentContact: string | null) => {
if (!currentContact) {
return;
}
const messages = await getMessages(currentContact);
console.log('Fetching messages for: ', currentContact);
messages.forEach(messageHandler);
};
function messageHandler(msg: ChatMessages) {
setMessages((prevMessages) => {
// Check if the message already exists in the state
if (!prevMessages.some((m) => m.message_id === msg.message_id)) {
return [...prevMessages, msg];
}
return prevMessages;
});
}
function updateContactStatus(contactObj: ContactObjProps, read: boolean) {
setContactsList((prevContacts) =>
prevContacts.map((contact) => {