As part of my ongoing effort to learn ReactJS I'm developing a simple page that will render a list of trends as follows:
On clicking the button "Get Trends" the list of trends is retrieved from a back-end server over websockets and displayed. It works as expected. Below is the corresponding source code:
import React, { Component } from 'react';
import './App.css';
class TrendRow extends Component {
render() {
return (
<tr>
<td>{this.props.onerow}</td>
</tr>
);
}
}
class TrendTable extends Component {
render() {
var rows = [];
for (var i=1; i<3; i++) {
rows.push(<TrendRow key={i} onerow={this.props.trends[i]}/>);
}
return (
<table>
<thead>
<tr>
<th>List of Trends</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
}
class App extends Component {
constructor() {
super();
this.state = {
ws: new WebSocket('ws://localhost:8025/websockets/TwitterWSService'),
getTrendsqueryString: 'GETTRENDS',
listoftrends: ['{"trend":"#Default","id":"0"}']
};
this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick = (event) => {
this.state.ws.send(this.state.getTrendsqueryString);
this.state.ws.onmessage = (event) => {
this.setState(prevState => ({listoftrends: prevState.listoftrends.concat(event.data)}));
}
}
render() {
return (
<div>
<button onClick={this.handleOnClick}>Get Trends</button>
<TrendTable trends={this.state.listoftrends} />
</div>
);
}
}
export default App;
Now when I try to convert the JSON string displayed into a JSON object using "JSON.parse" I get different types of errors based on where I parse it.
If I parse as shown below,
class TrendRow extends Component {
render() {
var jsonobject = JSON.parse(this.props.onerow);
return (
<tr>
<td>{jsonobject}</td>
</tr>
);
}
}
I get the below error:
"SyntaxError: Unexpected token u in JSON at position 0
...
var jsonobject = JSON.parse(this.props.onerow);
..."
A quick google search for the error message returned the following discussion but it's not very clear how to apply the solution to my use-case:
uncaught syntaxerror unexpected token U JSON
I understand that the error is due to value 'this.props.onerow' being undefined during the initial render and JSON.parse() trying to parse this object. Even initializing the "listoftrends" object with a default string does not solve the error.
If on the other hand I JSON.parse() as shown below,
handleOnClick = (event) => {
this.state.ws.send(this.state.getTrendsqueryString);
this.state.ws.onmessage = (event) => {
var jsonobject = JSON.parse(event.data);
this.setState(prevState => ({listoftrends: prevState.listoftrends.concat(jsonobject)}));
}
}
I get the error message:
Objects are not valid as a React child...
Google search leads me down another rabbit hole! Could someone please provide any other solutions for me to try?
