React performs Socket.io’s Callback function more than once

Asked

Viewed 168 times

-1

I am developing an application that works with React js in the frontend and a server in Node.js in the backend. On this server, I am using Socket.io to send notifications to the frontend when a certain routine occurs, so that the frontend can perform another action. It turns out, I realize that every time I send an event to the front, through the function Emit from socket.io, the frontend performs the callback function twice, as if two events were being issued. I’m looking for the mistake, but so far I haven’t found.

Follow the event issuer code (Socket.io):

const express = require("express");

const app = express();
const http = require("http");

const server = http.createServer(app).listen(4555, "127.0.0.1");

const io = require("socket.io").listen(server);

export default function notifyMiddleware(req, res, next) {
const { type, provider_id } = req.body;
const notification = {
    type,
    provider_id,
    date: new Date(),
};

if (notification !== null) {
    io.emit("notificacao", notification);
    res.status(200).json(notification);
    next();
} else {
    next();
}
}

function of Frontend(React) dealing with events:

  // Socket
  import socket from '../../services/socket';


  socket.on('notificacao', () => {
    console.log('notificacao');
  });

Socket.js:

import io from 'socket.io-client';

const socket = io('http://localhost:4555', {
 transports: ['websocket', 'polling', 'flashsocket'],
});

export default socket;

To test I trigger a call through the Insomnia to the socket. And the return is positive, the problem is that in the frontend the routine always runs twice. Follow picture: https://prnt.sc/u31u6q

1 answer

0

So far I did not understand the reason of the function perform more than once, however, I was able to solve by placing the function inside a React hook. Using the useEffect without dependency I managed to make it run only once, thus getting the connection open. Follow code that solved my problem:

useEffect(() => {
    socket.on('notificacao', () => {
    console.log('notificacao');
    });
}, []);
  • you have not put all the code in your question, but it must be because when updating other components it runs again. is a possibility.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.