Reputation:
I have two components, both of them are separated. I have to send a data from component1 to component2 through sockets. But my component2 listens for the event only once, after one time it is not listening to the event
Component1
class Component extends React.component{
socket = socketIOClient("http://localhost:5000")
sendData = () =>{
socket.emit("newData", {somedata})
}
render() {
return(
<button onClick={this.sendData} >Send</button>
})
}
Component2
class Component2 extends React.Component{
constructor(props) {
super(props)
this.state = {data}
}
socket = socketIOClient("http://localhost:4000")
componentDidMount() {
socket.on("newData", data =>
this.setState(data)
)}
render(){
return(<h1>{this.state.data.someAttribute} <h1/>)
}
}
Server
const io = socketIO(server)
io.on("connection", socket =>{
socket.on("newData", data=> socket.emit("newData"))
})
Component1 is sending data any number of times to the server (verified by console logging in server) But Component2 receives the data only on first time.
Upvotes: 1
Views: 1609
Reputation:
Found the solution,
The mistake is in the server side.
We have to use the actual io object to emit the events to other sockets those are connected to the server.
So the server side would be,
const io = socketIO(server)
io.on("connection", socket =>{
socket.on("newData", data =>{
io.sockets.emit("newData", data) //changed this line
})
})
Upvotes: 2