I get Uncaught TypeError: "Cannot read property '0' of undefined" error. I just can't figure out the issue.
Although the program run's fine & I'm getting the desired output. But the error...
Console screenshot Console screeshot / resp object
$(window).bind("load", function() {
var ws = new WebSocket("wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD");
ws.onopen = function(){
ws.send(JSON.stringify({"trade":"XBTUSD"}))
};
ws.onmessage = function (msg){
var resp = JSON.parse(msg.data);
console.log(resp);
var price = resp['data'][0].price; // can not read property 0 of undefined :/
console.log('Price is : ' + price);
};
});
Check resp/resp.data
is null or not. If resp/resp.data
is null, there are nothing at index 0
.
ws.onmessage = function (msg){
var resp = JSON.parse(msg.data);
console.log('Data : ' + data);
console.log('resp: ' + resp);
var price;
if(resp && resp.data){
price = resp.data[0].price; // can not read property 0 of undefined :/
}
console.log('Price is : ' + price);
//document.getElementById('btcPrice').value = price;
};