added sendContactsList function, fixed socket not working socket after login

This commit is contained in:
slawk0
2024-10-27 11:25:22 +01:00
parent cb99f174d2
commit 80412296aa
8 changed files with 53 additions and 40 deletions

View File

@@ -45,7 +45,6 @@ const router = createBrowserRouter([
function App() {
const [authorized, setAuthorized] = useState<boolean | null>(null);
return (
<AuthContext.Provider value={{ authorized, setAuthorized }}>
<RouterProvider router={router} />

View File

@@ -1,5 +1,8 @@
import { useForm, SubmitHandler } from 'react-hook-form';
import { sendContact, sendRequestHistorical } from '../../socket/socket.tsx';
import {
sendContact,
sendRequestHistoricalMessages,
} from '../../socket/socket.tsx';
import { Dispatch, SetStateAction, useEffect } from 'react';
type Input = {
@@ -26,13 +29,13 @@ function ContactForm({ contact, setContact, setMessages }: ContactInputProps) {
storedContact = storedContact = localStorage.getItem('contact');
if (storedContact) {
setContact(storedContact);
sendRequestHistorical(storedContact);
sendRequestHistoricalMessages(storedContact);
}
}, [setContact]);
const submitContact: SubmitHandler<Input> = (data) => {
setMessages([]);
sendRequestHistorical(data.contact);
sendRequestHistoricalMessages(data.contact);
localStorage.setItem('contact', data.contact);
setContact(data.contact);
sendContact({ contact: data.contact, read: true });

View File

@@ -1,4 +1,4 @@
import { socket } from '../../socket/socket.tsx';
import { sendRequestContactsList, socket } from '../../socket/socket.tsx';
import { useEffect, useState } from 'react';
type ContactList = {
username: string;
@@ -8,14 +8,23 @@ type ContactList = {
function ContactsList() {
const [contacts, setContacts] = useState<ContactList[]>([]);
useEffect(() => {
socket.on('contacts list', (contactsList: ContactList[]) => {
console.log('Received contacts: ', contactsList);
if (!socket) {
console.error('Socket not initialized');
return;
}
sendRequestContactsList();
socket.on('get contacts list', (contactsList: ContactList[]) => {
console.log('Received contacts list: ', contactsList);
setContacts(contactsList);
});
return () => {
if (!socket) {
console.error('Socket not initialized');
return;
}
socket.off('contacts list');
};
}, []);

View File

@@ -16,6 +16,11 @@ function MessagesArea({ messages, setMessages }: MessagesAreaProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!socket) {
console.error('Socket not initialized');
return;
}
function messageHandler(msg: ChatMessages) {
setMessages((prevMessages) => {
// Check if the message already exists in the state
@@ -30,7 +35,7 @@ function MessagesArea({ messages, setMessages }: MessagesAreaProps) {
console.log('Received message: ', msg);
messageHandler(msg);
});
socket.on('historical', (msg: ChatMessages[]) => {
socket.on('historical messages', (msg: ChatMessages[]) => {
console.log('Received historical messages: ', msg);
msg.forEach((historicalMsg) => {
@@ -38,6 +43,10 @@ function MessagesArea({ messages, setMessages }: MessagesAreaProps) {
});
});
return () => {
if (!socket) {
console.error('Socket not initialized');
return;
}
socket.off('chat message');
socket.off('historical');
};

View File

@@ -5,6 +5,8 @@ import ContactForm from '../components/chat/ContactForm.tsx';
import MessagesArea from '../components/chat/MessagesArea.tsx';
import { useState } from 'react';
import ContactsList from '../components/chat/ContactsList.tsx';
import { initializeSocket } from '../socket/socket.tsx';
import Cookies from 'js-cookie';
type ChatMessages = {
sender: string;
@@ -15,6 +17,11 @@ type ChatMessages = {
};
function Chat() {
const token = Cookies.get('token');
if (token) {
initializeSocket(token);
}
const [contact, setContact] = useState<string>('');
const [messages, setMessages] = useState<ChatMessages[]>([]);
return (

View File

@@ -1,7 +1,5 @@
import io from 'socket.io-client';
import Socket = SocketIOClient.Socket;
//TODO socket is trying to connect on login page fix it
let socket: Socket | null = null;
function initializeSocket(token: string): Socket | null {
@@ -22,13 +20,6 @@ function initializeSocket(token: string): Socket | null {
return socket;
}
function disconnectSocket() {
if (socket) {
socket.disconnect();
socket = null;
}
}
function sendMessage(message: string, recipient: string | null) {
if (!socket) {
console.error('Socket not initialized');
@@ -68,31 +59,30 @@ function sendContact(data: Contact) {
console.log('Sent contact: ', contact, 'status: ', read);
}
function sendRequestHistorical(recipient: string) {
function sendRequestHistoricalMessages(recipient: string) {
if (!socket) {
console.error('Socket not initialized');
return;
}
socket.emit('historical', { recipient: recipient });
socket.emit('historical messages', { recipient: recipient });
console.log('Requested historical messages for: ', recipient);
}
function sendGetContacts(username: string) {
function sendRequestContactsList() {
if (!socket) {
console.error('Socket not initialized');
return;
}
socket.emit('get contacts', username);
console.log('Requested contact list for: ', username);
socket.emit('get contacts list');
console.log('Requested contact list');
}
export {
initializeSocket,
disconnectSocket,
sendMessage,
sendContact,
sendRequestHistorical,
sendGetContacts,
sendRequestHistoricalMessages,
sendRequestContactsList,
socket,
};

View File

@@ -3,7 +3,6 @@ import { Navigate, Outlet } from 'react-router-dom';
import axios from 'axios';
import { useState, useEffect, useContext } from 'react';
import Cookie from 'js-cookie';
import { initializeSocket } from '../socket/socket.tsx';
import { AuthContext } from './AuthProvider.tsx';
export type UsernameType = {
@@ -26,11 +25,10 @@ function ProtectedRoutes() {
axios
.get('/api/auth/validate', { withCredentials: true })
.then((res) => {
.then(async (res) => {
setUsername(res.data.username);
console.log(res.data.username);
setAuthorized(true);
initializeSocket(token);
})
.catch((err) => {
setAuthorized(false);
@@ -41,7 +39,7 @@ function ProtectedRoutes() {
validateToken();
}, [setAuthorized]);
//TODO add loader
//TODO add spinning wheel
if (authorized === null) {
return null;
}

View File

@@ -49,14 +49,6 @@ function initializeSocket(io) {
}
socket.join(username); // join username room
const sendContactList = async () => {
const contacts = await getContacts(username);
io.to(username).emit("contacts list", contacts);
console.log("(socket) sent on 'contacts list: ", contacts);
};
await sendContactList(username);
socket.on("chat message", async (msg) => {
const { message, recipient, timestamp } = msg;
const sender = username;
@@ -88,9 +80,9 @@ function initializeSocket(io) {
});
});
socket.on("historical", async (recipient) => {
socket.on("historical messages", async (recipient) => {
const messages = await getMessages(username, recipient.recipient);
io.to(username).emit("historical", messages);
io.to(username).emit("historical messages", messages);
});
socket.on("add contact", (contactInf) => {
@@ -105,6 +97,12 @@ function initializeSocket(io) {
console.log("(socket) sent on 'contact' socket: ", { contact, read });
});
socket.on("get contacts list", async () => {
const contacts = await getContacts(username);
io.to(username).emit("get contacts list", contacts);
console.log("(socket) sent on 'get contacts list: ", contacts);
});
socket.on("disconnect", (reason) => {
console.log("(socket)", socket.id, " disconnected due to: ", reason);
});