Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

568
Views
useEffect se ejecuta dos veces una vez que recibe un mensaje de socket.io

Estoy creando una aplicación de chat simple usando react, express y socket.io.

Cada vez que el cliente envía el mensaje al servidor, el servidor transmitirá el mensaje a todos los usuarios. Tengo un problema al recibir un mensaje del servidor backend.

Cada vez que el usuario recibe un mensaje, useEffect se ejecutará dos veces en lugar de solo una.

 useEffect(() => { socket.on("broadcast_msg", (data) => { setMsg((list) => [...list, data]); }); }, [socket]);

PD. El servidor back-end emite de nuevo al front-end solo una vez. Gracias por cada respuesta :D

Código completo

 import React from "react"; import { useEffect } from "react"; import { useState } from "react"; function Chat(props) { const { socket, username, room } = props; const [input, setInput] = useState(""); const [msg, setMsg] = useState([]); // send msg to server const send_msg = (e) => { if (input !== "") { socket.emit("send_msg", { room: room, author: username, message: input, }); } }; // listen to boardcast msg useEffect(() => { socket.on("broadcast_msg", (data) => { setMsg((list) => [...list, data]); }); }, [socket]); return ( <div className="chat"> <div className="chat-header"></div> <div className="chat-body"> {msg.map((data) => { return ( <> <h1>{data.author}</h1> <h1>{data.room}</h1> <h1>{data.message}</h1> </> ); })} </div> <div className="chat-footer"> <input type="text" placeholder="Enter the message..." onChange={(e) => { setInput(e.target.value); }} /> <button onClick={send_msg}>Send</button> </div> </div> ); } export default Chat;
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

useEffect(() => { const eventListener = (data) => { setMsg((list) => [...list, data]); }; socket.on("broadcast_msg", eventListener); return () => socket.off("broadcast_msg", listener); }, [socket]);

Hacer con el oyente. Ejecute useEffect y limpie el oyente cuando se dispare nuevamente, esto debería funcionar. o ejecutar solo una vez cuando está montado.

 useEffect(() => { socket.on("broadcast_msg", (data) => { setMsg((list) => [...list, data]); }); }, []);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!