I've been able to establish connection to a websocket using a url being passed as props from the App.js to the Child component. On change of the value of the props, I want the already established websocket connection terminated and a new connection made with the new props value being passed.
The child component initiates the connection the moment it is mounted.
export class Stream extends Component {
state = {
ws: null
//url: this.props.value
};
componentDidMount() {
this.connect();
}
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value) {
this.disconnect(prevProps);
//this.connect(this.props.value);
}
}
componentWillUnmount() {
//socket.close();
}
connect = () => {
var socket = new WebSocket("wss://ws.dummy.net/");
let that = this; // cache the this
var subscribeMsg = {
event: "subscribe",
data: {
channel: "order" + this.props.value
}
};
function serializeData(data) {
//console.log(data);
that.setState({
ws: data //Map the serialized data to the state
});
}
// websocket onopen event listener
socket.onopen = () => {
socket.send(JSON.stringify(subscribeMsg));
console.log("connected websocket main component");
};
socket.onmessage = function(evt) {
var response = JSON.parse(evt.data);
console.log(response);
/**
* This switch statement handles message logic. It processes data in case of data event
* and it reconnects if the server requires.
*/
switch (response.event) {
case "data": {
serializeData(response.data);
break;
}
default: {
//console.log("Error in case assignment");
break;
}
}
};
// websocket onclose event listener
socket.onclose = e => {
console.log("Socket is closed");
};
// websocket onerror event listener
socket.onerror = err => {
console.error(
"Socket encountered error: ",
err.message,
"Closing socket"
);
};
};
disconnect = prevProps => {
var socket = new WebSocket("wss://ws.dummy.net/");
var unsubscribeMsg = {
event: "unsubscribe",
data: {
channel: "order" + prevProps.value
}
};
socket.close();
socket.onclose = e => {
socket.send(JSON.stringify(unsubscribeMsg));
console.log("DISCONNECT Socket is closed");
};
};
}