socket.emit() that I use inside the function is not working

Issue

In my application that I developed with React and node.js, the socket emit in the function is not working for some reason, when we press the button, we need to save the data in the backend and send this data to the other party in real time, in short, there will be a chat part.

Here you can see the code I wrote in React

  const sendMessage = async () => {
    if (message.trim() !== "") {
      try {
        const { data } = await axios.post(
          "http://localhost:5000/api/messages/",
          {
            content: message,
            chatId: chatId,
          },
          config
        );
        setMessage("");
        if (data) {
          const newData = {
            ...data,
            createdAt: new Date(),
          };
          socket.emit("new message", { newMessage: newData, room: chatId });
          setResponse((prev) => {
            return {
              ...prev,
              messages: [...prev.messages, newData],
            };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }
  };

Actually, this code was working a few hours ago, but now it stopped working for some reason I can’t find.

and here you can see that I’ve connected the socket

  useEffect(() => {
    socket = io("http://localhost:5000/");
    socket.on("connected", () => {
      return;
    });
    socket.emit("join chat", chatId);
  }, []);

I’m in the following situation, I performed a test emit operation in useEffect and it worked, but I can’t get it to work in this function

Here you can see the back end part

const io = new Server(server, {
  cors: {
    origin: " http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  socket.on("join chat", (room) => {
    socket.join(room);
  });
  socket.on("new message", ({ newMessage, room }) => {
    socket.to(room).emit("message recieved", newMessage);
  });

server.listen(5000, () => {
  console.log("working on 5000");
});
});

I would be very grateful if you could help me solve this problem. Thank you in advance

Solution

I finally solved the problem, it was an error due to my carelessness, I was sending a data in base64 format when I sent it and the emit process did not take place because it was overrun, I only increased the size limit on the server side.

Answered By – Batuhan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published