Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
1
Indexable
Never
// backend/server.js
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const http = require('http');
const socketIo = require('socket.io');
const { addUser, removeUser, getUser, getUsersInRoom } = require('./utils/users');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

const PORT = process.env.PORT || 5000;

// Set up MongoDB connection using Mongoose

// Set up routes for user authentication, group management, messages, etc.

// Set up Socket.io for real-time chat

server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});



// frontend/src/components/Chat/Chat.js
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import io from 'socket.io-client';

const Chat = ({ match }) => {
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);
  const user = useSelector((state) => state.user);
  const { groupId } = match.params;
  const ENDPOINT = 'http://localhost:5000';

  useEffect(() => {
    const socket = io(ENDPOINT);

    // Join the chat room with the user's ID and group ID
    socket.emit('join', { userId: user.id, groupId }, (error) => {
      if (error) {
        alert(error);
      }
    });

    // Clean up on unmount
    return () => {
      socket.emit('disconnect');
      socket.off();
    };
  }, [ENDPOINT, user.id, groupId]);

  // Handle sending messages
  const sendMessage = (event) => {
    event.preventDefault();
    if (message) {
      socket.emit('sendMessage', { message, groupId }, () => setMessage(''));
    }
  };

  // Display messages
  useEffect(() => {
    socket.on('message', (message) => {
      setMessages([...messages, message]);
    });
  }, [messages]);

  return (
    <div className="chat">
      {/* Render chat messages and input for sending messages */}
    </div>
  );
};

export default Chat;