Reputation: 55
socket.on executes more than one time that causes if a user sends one message it will execute more three times that causes to dispatch more three times
useEffect(() => {
setSocket(io("http://localhost:5000/chat", { query: { token: localStorage.getItem("jwtToken") } }));
socket.on("send", function(data){
dispatch(sendMessage(data));
})
}, [socket, setSocket, dispatch])
how to fix this issue
Upvotes: 0
Views: 23
Reputation: 4353
useEffect(() => setSocket(io("http://localhost:5000/chat", { query: { token: localStorage.getItem("jwtToken") } })), [localStorage.getItem("jwtToken")]);
useEffect(() => {
const listener = function(data){
dispatch(sendMessage(data));
};
socket.addEventListener("send", listener);
return () => socket.removeEventListener("send", listener);
}, [socket])
Upvotes: 1