Emitting from Server is not working correctly

27 views Asked by At

Here is my client code:

import io from 'socket.io-client';

const FriendOpts = ({ user2Email, locationState = null, component = null }) => {
    const auth = useContext(AuthContext);
    const socket = io("http://localhost:8000/friends", {
        query: {
            email: auth.email
        },
    });

    useEffect(() => {
        socket.on('connect', () => {
            console.log(`Connected to the friends namespace`);
        });

        // Listen for incoming friend requests
        socket.on('receiveFriendRequest', (senderEmail) => {
            console.log(senderEmail)
        });
    }, []);

const addFriend = (potentialFriend) => {
        socket.emit("sendFriendRequest", potentialFriend)
    };

Here is my server code:

// Define a namespace for friends
const friendsNamespace = io.of('/friends');

const userSockets = new Map();

friendsNamespace.on('connection', (socket) => {
  // When a user connects, get their email from the query parameter
  const email = socket.handshake.query.email;
  console.log(email, "joined")
  // Store the user's socket with their email
  userSockets.set(email, socket);

  // Listen for friend requests and emit to the recipient
  socket.on('sendFriendRequest', (recipientEmail, senderEmail) => {
    const recipientSocket = userSockets.get(recipientEmail);

    if (recipientSocket) {
      console.log("sending to friend req to", recipientEmail)
      recipientSocket.emit('receiveFriendRequest', senderEmail);
    }
  });
});

server.listen(8000, () => {
    console.log(`Server on 8000`);
})

I've included the relevant code. This code is able to connect to the namespace, and even the log "sending friend req to", but the receiveFriendRequest is not working. I'm not sure if it is emitting incorrectly or receiving incorrectly. What is the issue?

1

There are 1 answers

0
jfriend00 On

Move your client-side socket.on(...) handlers out of the useEffect() callback to the same level as const socket = io("http://localhost:8000/friends", ...). You want those event handlers registered immediately as soon as the socket exists.