I'm trying to send message using Socket.io. When I open chat and send messages it works correctly. The problem is when I change the page/route, then comeback to chat(rerender), send message and recieve data from socket my socket function socket.on executes multiple times(how many times have I rerendered). I tried different variants, but didn't solve. Thanks!
The client code
const ENDPOINT = 'http://localhost:8080'
let socket
let ChatPage = (props) => {
let test = useSelector(getMessages)
const [messages, setMessages] = useState(props.messages)
useEffect(() => {
socket = io(ENDPOINT)
}, [])
useEffect(() => {
setMessages(props.messages)
}, [props.messages])
useEffect(() => {
socket.on('incMsg', (msg) => {
props.setRealMessage(msg)
setMessages((prevMessages) => {
return [...prevMessages, msg]
})
})
}, [])
let sendMessage = (msg) => {
props.setRealMessage(msg)
socket.emit('msg', msg)
}
debugger
return (
<div style={{ display: 'flex', width: '-webkit-fill-available' }}>
<NavPanel />
<Messenger sendMessage={sendMessage} />
</div>
);
}
const mapStateToProps = (state) => {
return {
messages: state.messenger.messages
}
}
export default compose(
connect(mapStateToProps, { setRealMessage }),
withRouter
)(ChatPage);
The server code
const http = require('http').Server(app)
const socketio = require('socket.io')
const io = socketio(http)
io.listen(8080);
io.on('connection', (socket) => {
socket.on('msg', (msg)=>{
console.log(msg);
socket.broadcast.emit('incMsg', msg)
})
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…