I wrote this code where I get some data from a function on the server side and that function gives back some data that is then relayed to the front end vis socket.io in node and react
however the server is successfully emitting the data but the client side is not receiving it, the client is making connection with the server but it is not taking in the data when it is told to
Here is the code
This is the *server side
socket.on("fetchStartUpProjects", async (data) => {
console.log("Fetch Function Recieved",data)
await getprojectfolders(data, (err, directories) => {
if(err){
console.error("There was some error")
socket.emit('error', err.message)
}else{
console.log("emitting", directories)
socket.emit('directories', directories);
console.log(directories, "are the directories")
}
})
});
in the else side, the data is successfully stored in "directories" and both console.log are been executed meaning the socket.emit is working
Here is the client side
import logo from "./logo-closeup-tp.png";
import "./ProjectRoom.scss";
import io from 'socket.io-client';
import toast, { Toaster } from 'react-hot-toast';
import { useState, useEffect } from "react";
const socket = io('http://localhost:3000',{
transports: ['websocket', 'polling'],
withCredentials: true
});
export const ProjectRoom = () => {
const [directories, setDirectories] = useState([]);
useEffect(() => {
// Event listener for socket connection
socket.on('connect', () => {
console.log('Connected to server:', socket.id);
});
// Event listener for directories data
// socket.on('directories', async (directories) => {
// await setDirectories(directories);
// await console.log("recieved", directories)
// });
socket.on('directories', async (data) => {
await console.log('Received directories:', data);
await setDirectories(data);
});
// Cleanup on component unmount
return () => {
socket.off('connect');
socket.off('directories');
};
}, []);
here the "connect" is happening properly but the "directories" isnt working
I tried changing some stuff in both in the front and the backend but to no avail.. I even asked chatgpt but it didnt help
2
Answers
on the server side you have to add io.sockets.on(‘connection’, function
like this below
Try to put socket.on(‘directories’ into socket.on(‘connect’)
like above.
what means socket.off(‘connect’); ??? also try to comment this row please