-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
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.
– novic