I am sending through socket.io
an object to a react
application like this:
function getApiAndEmit(socket, quote)
{
try
{
var { ticker, type, price, size, timestamp } = quote;
socket.emit("FromAPI", quote);
//console.log(ticker, type, price, size, timestamp)
}
catch (error)
{
console.error(`Error: ${error.code}`);
}
};
When I try to render it on the client side, I get the error:
If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.
What is the correct way to render the fields on the web browser with react
?
The code
import React, { Component } from "react";
import socketIOClient from "socket.io-client";
class App extends Component {
constructor() {
super();
this.state = {
response: {},
endpoint: "http://127.0.0.1:4001"
};
}
componentDidMount() {
const { endpoint } = this.state;
const socket = socketIOClient(endpoint);
socket.on("FromAPI", data => this.setState({ response: data }));
}
render() {
const { response } = this.state;
return (
<div style={{ textAlign: "center" }}>
{response
? <ul>
Quote: {response}
</ul>
: <p>Loading...</p>}
</div>
);
}
}
export default App;
React can't render objects. To bypass the error immediately, put in the following:
{
response
? <ul><li>Quote: {JSON.stringify(response)}</li></ul>
: <p>Loading...</p>
}
response
is an array of Strings:<ul>Quote: { response.map((item, index) => (<li key={index}>{item}</li>)) }</ul>
response
is an array of objects:<ul>Quote: { response.map((item, index) => (<li key={index}>{item.quote}</li>)) }</ul>
response
is an object:<ul><li>Quote: {response.quote}</li></ul>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments