Hello. I’m not able to use the data from the websocket because it is undefined. I have a variable called data and I initialize it with the json from the websocket. It is displayed in the console inside the client.onmessage block but when I try to use it below I get this error: Uncaught TypeError: Cannot read properties of undefined (reading ‘BEST’) . How could I solve not to have the data undefined?
const client = new W3CWebSocket("wss://host.net");
var dataFromServer;
client.onopen = () => {
var sendData = {
eventId: "16",
};
client.send(JSON.stringify(sendData));
console.log("WebSocket Client Connected!");
};
client.onmessage = function (message) {
dataFromServer = JSON.parse(message.data);
console.log("got reply: ", dataFromServer);
};
client.onerror = function () {
console.log("Connection Error");
};
console.log(dataFromServer); // undefined
var best = dataFromServer.BEST.slice(0, 3); // Uncaught TypeError: Cannot read properties of undefined (readning 'BEST')
The code inside the callback runs when an event is fired. The code outside the callback runs immediately and at that time the variable has not been assigned anything so it’s undefined. Use the data inside the callback directly, or pass it to a function.
Simple click handler example:
<button>Click me</button>
let outsideScope;
document
.querySelector("button")
.addEventListener("click", ({ currentTarget }) => {
// Runs when the event fires
outsideScope = currentTarget.textContent;
console.log("outsideScope inside callback", outsideScope);
});
// Runs before the event fires
console.log("outsideScope outside callback", outsideScope);
// 1. outsideScope outside callback undefined
// 2. outsideScope inside callback Click me
The console.log inside the callback is an example of direct usage. For the function usage, you just call the function and pass it an argument then use that inside the function.
client.onmessage = function (message) {
const best = message.data.BEST.slice(0, 3);
logBest(best);
};
function logBest(data) {
console.log(data)
}
Log out the data you get back (message) and make sure you know what the data looks like. In all likelihood, it just means you are not accessing the correct properties.
Yeah, there are 3 separate messages in JSON but the first one does not have the BEST value, could this be the problem right? Is there a way chekc if the value not present then do nothing or have a default instead?