ReactJS - TypeError: Cannot read property '0' of undefined
this.ws.onmessage = e => {
var tbox = JSON.parse(e.data);
this.setState({
user : this.state.usernames.concat(tbox.data[0].user),
messages : this.state.messages.concat(tbox.data[0].message)
})
console.log(tbox.data[0].user + ': ' + tbox.data[0].html);
I'm trying to parse, setState and display data in realtime (in a Ant Design List component) from a public websocket api.
I managed to get thus far but if someone can better help me steer in the right direction, that would be much appreciated!
const URL = 'wss://www.bitmex.com/realtime?subscribe=chat:1'
const data = [
{
user: 'buythediplosers',
message: 'im over here waiting for nothing lol',
time: '4:20 AM', /*TODO: let the user set their timezone*/
},
];
class Trollbox extends Component {
constructor(props) {
super(props);
this.state = {
usernames: [],
messages: [],
timestamps: [],
}
}
ws = new WebSocket(URL)
componentDidMount() {
this.ws.onopen = () => {
console.log('connected')
}
this.ws.onmessage = e => {
var tbox = JSON.parse(e.data);
this.setState({
user : this.state.usernames.concat(tbox.data[0].user),
messages : this.state.messages.concat(tbox.data[0].message)
})
console.log(tbox.data[0].user + ': ' + tbox.data[0].html);
}
this.ws.onclose = () => {
console.log('disconnected')
this.setState({
ws: new WebSocket(URL),
})
}
}
render() {
return (
<div>
<div>
<List
itemLayout="horizontal"
dataSource={data}
renderItem={item => (
<List.Item>
<List.Item.Meta
description={
<div>
<p>
<b>{item.user}</b>: {item.message} {item.time}
</p>
</div>
}
/>
</List.Item>
)}
/>
</div>
...
console.log(tbox.data[0].user + ': ' + tbox.data[0].html);
shows me what I want to see in the console, which is a step forward for me:

console.log(this.state.usernames + ': ' + this.state.messages);
though, this bunches it all up unlike the previous line while still giving me an error:
EDIT: JSON sample:
{
"table":"chat",
"action":"insert",
"keys":[
"id"
],
"data":[
{
"channelID":1,
"date":"2019-11-27T07:20:30.862Z",
"fromBot":false,
"html":"Keepitreal: ok bruh\n",
"id":43087881,
"message":"Keepitreal: ok bruh",
"user":"cryxix"
}
],
"filterKey":"channelID"
}

Shows that the first 3 responses you are getting are different than the ones you are expecting, and don't have key called user in it, hence why you are getting that error. You can skip over it by adding a conditional like: