ERR: obj are not valid as react child
I am using create-react-app with websocketserver backend. I am getting the error “Objects are not valid as a React child (found: object with keys {id, status}). If you meant to render a collection of children, use an array instead.”
my backend
std::string out = "[{"id": "" + Event->getID().asString() + "","; if (auto stateEvent = dynamic_cast<const StateReport*>(Event.get())) { out += ""State-Event": ""; out += stateToString(stateEvent->getState()); out += ""}]"; } else out += ""Unknown event": ""}]"; out += "n"; objcomm::Data resp; resp._data = (const std::uint8_t*)out.c_str();
react code
componentDidMount() { client.onmessage = (message) => { var data = message.data; this.setState({dataFromServer: data}); console.log(message.data); }; } render() { if(!this.state.dataFromServer){ return "loading" } else if(this.state.dataFromServer && this.state.dataFromServer.length >0){ return( this.state.dataFromServer.map(data => ( {data} )) ); } }
console log of message.data
[{"id": "1.2","State-Event" : "Running"}]
I wanted to access something like this.state.datafromServer.map(data => {data.id}) but when i do this i get datafromServer.map is not a func
what am i doing wrong.
Answer
Most likely, during the first execution of render()
the value of this.state.dataFromServer
will still be undefined
, which explains the “datafromServer.map is not a function” error.
During the next render()
execution it should have been set (as a result of the API having been called), and then you can use it.
This is a very common situation. See below for an example of how to deal with it:
render() { if (!this.state.dataFromServer) return <p>Loading...</p>; return this.state.dataFromServer.map(item => this.createElement(item)); }
The this.createElement
is just an example here, it is up to you to either implement it, or to do something else with each item
. A very simple (starter) implementation could be:
createElement = (item) => <p>id: {item.id}</p>