Reputation:
I am trying to make a socket connection to my backend through my front end, but sme successfully
I declared my socket in my state and then opened the connection, but I don't know why this error:
code:
class App extends Component {
constructor(props, context){
super(props, context);
this.state = {
queue: '',
socket: null
};
}
componentDidMount() {
// io() not io.connect()
this.state.socket = io('http://localhost:9000');
this.state.socket.on('queue', (queue) => {
this.setState({
queue
})
});
this.state.socket.open();
}
componentWillUnmount() {
this.state.socket.close();
}
render() {
return (
<div>
<p> Queue: {this.state.queue} </p>
</div>
)
}
}
Upvotes: 0
Views: 111
Reputation: 1
Don't set a state object directly. Set it with setState({}).
componentDidMount() {
// io() not io.connect()
const socket = io('http://localhost:9000');
socket.on('queue', (queue) => {
this.setState({
queue,
});
});
socket.open();
this.setState({ socket });
}
Upvotes: 0
Reputation: 217
You should not set the state directly by using this.state.socket = ...
Instead of setting socket
as a state, you can try using this.socket
.
class App extends Component {
constructor(props, context){
super(props, context);
this.socket = null;
this.state = {
queue: '',
};
}
componentDidMount() {
// io() not io.connect()
this.socket = io('http://localhost:9000');
this.socket.on('queue', (queue) => {
this.setState({
queue: queue
})
});
this.socket.open();
}
componentWillUnmount() {
this.socket.close();
}
render() {
return (
<div>
<p> Queue: {this.state.queue} </p>
</div>
)
}
}
Upvotes: 1